From 327452622e3081c81b05916c61454a9fd97d992d Mon Sep 17 00:00:00 2001 From: flosch Date: Sun, 25 Jul 2010 18:22:26 +0200 Subject: [PATCH] Handle DBRefs correctly within Q objects. Closes #55 --- mongoengine/queryset.py | 11 +++++++++++ tests/queryset.py | 14 ++++++++++++++ 2 files changed, 25 insertions(+) diff --git a/mongoengine/queryset.py b/mongoengine/queryset.py index e176c54c..00a7f7a2 100644 --- a/mongoengine/queryset.py +++ b/mongoengine/queryset.py @@ -133,6 +133,17 @@ class Q(object): if isinstance(value, pymongo.objectid.ObjectId): 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 operation_js = op_js % { 'field': key, diff --git a/tests/queryset.py b/tests/queryset.py index 3691d89e..8cbd9a40 100644 --- a/tests/queryset.py +++ b/tests/queryset.py @@ -1304,6 +1304,20 @@ class QTest(unittest.TestCase): query = ['(', {'age__gte': 18}, '&&', {'name': 'test'}, ')'] 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__': unittest.main()