使用MongoEngine和Q构造查询会抛出InvalidQueryError

时间:2015-04-05 10:33:21

标签: python django mongoengine

我正在尝试使用orMongoEngine类构建一个简单的django.db.models.Q查询。

我的代码(从./manage.py shell运行)是:

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

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

我的models.py只是

from mongoengine import *

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

我尝试了几个不同的版本,并且总是会出现以下错误:

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?

我使用Python 2.7.6和以下软件包:

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

我是Python和Django的新手,但这看起来相当简单。我做错了什么?

1 个答案:

答案 0 :(得分:11)

事实证明我导入了错误的Q类。对于MongoEngine,它应该是:

from mongoengine.queryset.visitor import Q