Constructing queries with MongoEngine and Q throws InvalidQueryError

人盡茶涼 提交于 2020-06-25 10:14:47

问题


I am trying to construct a simple or query using MongoEngine and the django.db.models.Q class.

My code (run from ./manage.py shell) is:

from db.models import User
from django.db.models import Q

User.objects.filter(Q(username='foo') | Q(email='bar'))

My models.py is just

from mongoengine import *

class User(Document):
    username = StringField()
    email = StringField()

I have tried several different versions, and always get the following error:

Traceback (most recent call last):
  File "<console>", line 1, in <module>
  File "venv/lib/python2.7/site-packages/mongoengine/queryset/base.py", line 193, in filter
    return self.__call__(*q_objs, **query)
  File "venv/lib/python2.7/site-packages/mongoengine/queryset/base.py", line 109, in __call__
    raise InvalidQueryError(msg)
InvalidQueryError: Not a query object: (OR: ('username', 'foo'), ('email', 'bar')). Did you intend to use key=value?

I'm using Python 2.7.6 with the following packages:

dj-database-url==0.3.0
dj-static==0.0.6
Django==1.8
django-toolbelt==0.0.1
gunicorn==19.3.0
mongoengine==0.9.0
psycopg2==2.6
pymongo==2.8
static3==0.5.1

I am new to Python and Django, but this seems fairly simple. What am I doing wrong?


回答1:


It turns out that I was importing the wrong Q class. For MongoEngine it should be:

from mongoengine.queryset.visitor import Q


来源:https://stackoverflow.com/questions/29456379/constructing-queries-with-mongoengine-and-q-throws-invalidqueryerror

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