MongoDB using an OR clause in mongoengine

ⅰ亾dé卋堺 提交于 2019-11-29 13:26:32

The mongoengine documentation is apparently incorrect in this case. Instead of using the bitwise operators "&" and "|", you should use the standard operators "and" and "or".

So your first query becomes:

query = ContentItem.objects.filter( (Q(account=account) and Q(public=True)) or  (Q(account=account) and Q(creator=logged_in_user)) ).order_by('-last_used')

The correct way to do the query is to use bitwise operations | and & the way you wrote it in your question:

query = ContentItem.objects.filter( (Q(account=account) & Q(public=True)) |  (Q(account=account) & Q(creator=logged_in_user)) ).order_by('-last_used')

Note: using the standard Python boolean operators and and or will not work. This is explained in the MongoEngine documentation.

MongoEngine docs say otherwise. Please check this:

https://github.com/MongoEngine/mongoengine/blob/master/tests/queryset/transform.py

line 134

def test_raw_query_and_Q_objects(self):

    query = Foo.objects(__raw__={'$nor': [{'name': 'bar'}]})._query
    self.assertEqual(query, {'$nor': [{'name': 'bar'}]})

    q1 = {'$or': [{'a': 1}, {'b': 1}]}
    query = Foo.objects(Q(__raw__=q1) & Q(c=1))._query
    self.assertEqual(query, {'$or': [{'a': 1}, {'b': 1}], 'c': 1})

you are probably import the wrong Q

from mongoengine.queryset.visitor import Q as mongo_Q

from django.db.models import Q as normal_Q

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!