Attribute Error when building nested index for DictField in DynamicDocument
pymongo==3.2.2 mongoengine==0.10.6
class ABC(DynamicDocument):
meta = {
'indexes':[
'nested.a',
'nested.b'
]
}
nested = mongo.DictField()
This fails with:
AttributeError: 'DictField' object has no attribute 'document_type'
However if base class is just Document, it seems to be working.
Also this used to work for mongoengine==0.8.7 pymongo==2.8
I also see something similar when running a query
class MandrillLog(DynamicDocument):
meta = {'collection': 'mandrill_events'}
event = StringField()
msg = DictField()
ts_datetime = DateTimeField(default=datetime.min)
MandrillLog.objects(event__in=['click', 'open'], msg__metadata__user_id=str(u.id), ts_datetime__gte=since)
Results in:
InvalidQueryError
Traceback (most recent call last)<ipython-input-25-c3d07ef4167f> in <module>()
4
----> 5 emails = list(chain.from_iterable([MandrillLog.objects(event__in=['click', 'open'], msg__metadata__user_id=str(u.id), ts_datetime__gte=since) for u in org.users]))
/home/matt/work/knowsis/env/lib/python2.7/site-packages/mongoengine/queryset/queryset.pyc in _iter_results(self)
78 raise StopIteration
79 if len(self._result_cache) <= pos:
---> 80 self._populate_cache()
81
82 def _populate_cache(self):
/home/matt/work/knowsis/env/lib/python2.7/site-packages/mongoengine/queryset/queryset.pyc in _populate_cache(self)
90 try:
91 for i in xrange(ITER_CHUNK_SIZE):
---> 92 self._result_cache.append(self.next())
93 except StopIteration:
94 self._has_more = False
/home/matt/work/knowsis/env/lib/python2.7/site-packages/mongoengine/queryset/base.pyc in next(self)
1405 raise StopIteration
1406
-> 1407 raw_doc = self._cursor.next()
1408 if self._as_pymongo:
1409 return self._get_as_pymongo(raw_doc)
/home/matt/work/knowsis/env/lib/python2.7/site-packages/mongoengine/queryset/base.pyc in _cursor(self)
1479 .find(self._query, **self._cursor_args)
1480 else:
-> 1481 self._cursor_obj = self._collection.find(self._query,
1482 **self._cursor_args)
1483 # Apply where clauses to cursor
/home/matt/work/knowsis/env/lib/python2.7/site-packages/mongoengine/queryset/base.pyc in _query(self)
1513 def _query(self):
1514 if self._mongo_query is None:
-> 1515 self._mongo_query = self._query_obj.to_query(self._document)
1516 if self._class_check and self._initial_query:
1517 if "_cls" in self._mongo_query:
/home/matt/work/knowsis/env/lib/python2.7/site-packages/mongoengine/queryset/visitor.pyc in to_query(self, document)
88 def to_query(self, document):
89 query = self.accept(SimplificationVisitor())
---> 90 query = query.accept(QueryCompilerVisitor(document))
91 return query
92
/home/matt/work/knowsis/env/lib/python2.7/site-packages/mongoengine/queryset/visitor.pyc in accept(self, visitor)
153
154 def accept(self, visitor):
--> 155 return visitor.visit_query(self)
156
157 @property
/home/matt/work/knowsis/env/lib/python2.7/site-packages/mongoengine/queryset/visitor.pyc in visit_query(self, query)
76
77 def visit_query(self, query):
---> 78 return transform.query(self.document, **query.query)
79
80
/home/matt/work/knowsis/env/lib/python2.7/site-packages/mongoengine/queryset/transform.pyc in query(_doc_cls, **kwargs)
59 fields = _doc_cls._lookup_field(parts)
60 except Exception, e:
---> 61 raise InvalidQueryError(e)
62 parts = []
63
InvalidQueryError: 'DictField' object has no attribute 'document_type'
Unusually, if I change the field to a DynamicEmbeddedDocument then there is no error...
class MandrillLog(DynamicDocument):
meta = {'collection': 'mandrill_events'}
class Msg(DynamicEmbeddedDocument):
pass
event = StringField()
msg = EmbeddedDocumentField(Msg, default=Msg)
ts_datetime = DateTimeField(default=datetime.min)
I've been having similar issues with DictFields in DynamicDocuments. Posted this to Stack Overflow:
http://stackoverflow.com/questions/36877900/problems-with-dictfield-in-mongoengine-dynamicdocument
Interesting. If you look inside mongoengine/fields.py, you will see that the following fields do have document_type attribute: EmbeddedDocumentField, EmbeddedDocumentListField, CachedReferenceField. That's probably why changing the DictField to an EmbeddedDocumentField worked.
Interesting how mongoengine fails to support one of the basic mongodb features, which is: documents are schema-less (dynamic) and can include another dynamic embedded document inside it (dicts). To me this is the basic bare-bone stuff that needs to work flawlessly, everything else are bells and whistles. I dont see how one can call a release stable without this main feature supported. Sorry if it sounds like a rant, but this caused me great deal of annoyance, trying to work around it. I might just downgrade to 0.8/2.8 versions.
I think I figured out what the issue is. Check out the Stack Overflow thread I posted earlier. However, as I stated in the Stack Overflow thread, I still cannot figure out how the field variable is set in the first place. Any ideas?
I managed to get around this issue by modifying the code in the __lookup_field function in mongoengine/base/document.py (around line 974). I changed this:
ReferenceField = _import_class('ReferenceField')
GenericReferenceField = _import_class('GenericReferenceField')
if isinstance(field, (ReferenceField, GenericReferenceField)):
raise LookUpError('Cannot perform join in mongoDB: %s' %
'__'.join(parts))
if hasattr(getattr(field, 'field', None), 'lookup_member'):
new_field = field.field.lookup_member(field_name)
elif cls._dynamic and (isinstance(field, DynamicField) or
getattr(getattr(field, 'document_type'), '_dynamic')):
new_field = DynamicField(db_field=field_name)
else:
# Look up subfield on the previous field or raise
try:
new_field = field.lookup_member(field_name)
except AttributeError:
to
ReferenceField = _import_class('ReferenceField')
GenericReferenceField = _import_class('GenericReferenceField')
if isinstance(field, (ReferenceField, GenericReferenceField)):
raise LookUpError('Cannot perform join in mongoDB: %s' %
'__'.join(parts))
if hasattr(getattr(field, 'field', None), 'lookup_member'):
new_field = field.field.lookup_member(field_name)
elif cls._dynamic and (isinstance(field, DynamicField) or
getattr(getattr(field, 'document_type', None), '_dynamic', None)):
new_field = DynamicField(db_field=field_name)
else:
# Look up subfield on the previous field or raise
try:
new_field = field.lookup_member(field_name)
except AttributeError:
All I did was add 'None' to the tests in the 'elif' line. That line was not present in MongoEngine 0.8.7, so DictFields in DynamicDocuments would just fall to the try/except block. Adding 'None' to the getattr functions achieves this.
I tested the new code by querying some DynamicDocuments with DictFields and some with EmbeddedDocuments, and so far, it has worked.
Thanks for the feedback. Would you like to submit a PR?
Thanks for your reply! Still waiting to hear back from my company to see if I am allowed to submit a PR. I'll go bug them again.
I will post a PR. its a 1 line change
On Jun 15, 2016, at 1:29 PM, Christopher Spears [email protected] wrote:
Thanks for your reply! Still waiting to hear back from my company to see if I am allowed to submit a PR. I'll go bug them again.
— You are receiving this because you authored the thread. Reply to this email directly, view it on GitHub https://github.com/MongoEngine/mongoengine/issues/1278#issuecomment-226259745, or mute the thread https://github.com/notifications/unsubscribe/ABL_iTzVkakOYE5sQdTi0DL2SqsX_A2eks5qMDZegaJpZM4IDN6H.
Great! Thank you!
Should be fixed with https://github.com/MongoEngine/mongoengine/pull/1313. Please check and reopen if it is not the case.
Thanks for reporting and fixing this.