Handle DBRefs correctly within Q objects. Closes #55

This commit is contained in:
flosch 2010-07-25 18:22:26 +02:00
parent 13316e5380
commit 327452622e
2 changed files with 25 additions and 0 deletions

View File

@ -133,6 +133,17 @@ class Q(object):
if isinstance(value, pymongo.objectid.ObjectId): if isinstance(value, pymongo.objectid.ObjectId):
value = unicode(value) value = unicode(value)
# Handle DBRef
if isinstance(value, pymongo.dbref.DBRef):
# this.created_user.$id == "4c4c56f8cc1831418c000000"
op_js = '(this.%(field)s.$id == "%(id)s" &&'\
' this.%(field)s.$ref == "%(ref)s")' % {
'field': key,
'id': unicode(value.id),
'ref': unicode(value.collection)
}
value = None
# Perform the substitution # Perform the substitution
operation_js = op_js % { operation_js = op_js % {
'field': key, 'field': key,

View File

@ -1304,6 +1304,20 @@ class QTest(unittest.TestCase):
query = ['(', {'age__gte': 18}, '&&', {'name': 'test'}, ')'] query = ['(', {'age__gte': 18}, '&&', {'name': 'test'}, ')']
self.assertEqual((q1 & q2 & q3 & q4 & q5).query, query) self.assertEqual((q1 & q2 & q3 & q4 & q5).query, query)
def test_q_with_dbref(self):
"""Ensure Q objects handle DBRefs correctly"""
class User(Document):
pass
class Post(Document):
created_user = ReferenceField(User)
user = User.objects.create()
Post.objects.create(created_user=user)
self.assertEqual(Post.objects.filter(created_user=user).count(), 1)
self.assertEqual(Post.objects.filter(Q(created_user=user)).count(), 1)
if __name__ == '__main__': if __name__ == '__main__':
unittest.main() unittest.main()