mongoengine
mongoengine copied to clipboard
Document inherited from DynamicDocument throws ValidationError on EmbeddedDocument field
Document inherited from DynamicDocument throws Validation Error: Invalid embedded document instance provided to an EmbeddedDocumentField.
class MyEmbDoc(EmbeddedDocument):
emb_field = StringField()
class MyDoc(DynamicDocument):
emb_doc = EmbeddedDocumentField(MyEmbDoc, )
creating an instance of MyDoc from data in the form:
data_dict = { "emb_doc": {"emb_field": "foo"} }
using MyDoc(**data_dict) will throw a "ValidationError (MyDoc:None) (Invalid embedded document instance provided to an EmbeddedDocumentField: ['emb_doc'])",
However, the same MyDoc class if inherited from Document class does not have this issue. Debugging shows that the issue lies in BaseDocument init method:
if self._dynamic: dynamic_data = {} for key, value in values.items(): if key in self._fields or key == '_id': setattr(self, key, value) elif self._dynamic: dynamic_data[key] = value else: FileField = _import_class('FileField') for key, value in values.items(): if key == '__auto_convert': continue key = self._reverse_db_field_map.get(key, key) if key in self._fields or key in ('id', 'pk', '_cls'): if __auto_convert and value is not None: field = self._fields.get(key) if field and not isinstance(field, FileField): **value = field.to_python(value)** setattr(self, key, value) else: self._data[key] = value
field.to_python(value) calls the _from_son method that casts the nested dictionary into an object of class MyEmbDoc for instances of Document subclasses but not for those of DynamicDocument.
I am also suffering from this issue! Any guidance would be very appreciated. I am able to re-produce the results above.
Any updates on this? I've encountered the same problem and haven't found any solution/suggestion yet. @CameronJRAllan @abhiman24 @rozza @bagerard please, could you advice on this. Thanks on advance.
UPD:
Solved this by using document.objects.insert(data_dict) Though it isn't a good solution since I'm skipping validation in this case. Still, can't understand why in case of DynamicDocument we can't use dict for EmbeddedDocument field.
I am also having this issue. Is this a bug?
I am still facing issues with this. Any solutions?
I also have the same problem, and then use from_json to build the instance, it works. such as: MyDoc.from_json(json.dumps(data_dict))