Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stack up multiple filter queries in mongoengine

How is it possible to run the following:

someQuerySet.filter(keyword='someKey')
someQuerySet.filter(keyword='someOtherKey')

I get InvalidQueryError: Duplicate query conditions whenever I try to do that. I know it's possible to filter by a list of values, but right now, I need to do individual filters.

Later edit: I'm actually using:

someQuerySet.filter(keyword__ne='someKey')
someQuerySet.filter(keyword__ne='someOtherKey')
like image 359
Mihai Neacsu Avatar asked Aug 16 '26 04:08

Mihai Neacsu


2 Answers

You could build up Q objects like this:

from django.db.models import Q

filters = Q(keyword='someKey')
…
filters = filters | Q(keyword='someOtherKey')

someQuerySet.filter(filters)

This will basically create a WHERE clause like this: WHERE keyword = 'someKey' OR keyword = 'someOtherKey'

I am doing this from memory, so let me know if this doesn't work, and I will look into some of my past code.

like image 152
jproffitt Avatar answered Aug 17 '26 19:08

jproffitt


The reason for the error is because by default the queries parameters AND. So you are asking for keyword="SomeKey" AND keyword="SomeOtherKey" which can never be true.

You could use Q objects to or like: http://docs.mongoengine.org/en/latest/guide/querying.html#advanced-queries or do a $in where the value matches any in a list eg: keyword__in=["SomeKey", "SomeOtherKey"]

like image 25
Ross Avatar answered Aug 17 '26 21:08

Ross



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!