Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Constructing queries with MongoEngine and Q throws InvalidQueryError

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?

like image 941
zelanix Avatar asked Apr 05 '15 10:04

zelanix


1 Answers

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

from mongoengine.queryset.visitor import Q
like image 180
zelanix Avatar answered Sep 22 '22 15:09

zelanix