Dynamically build complex queries using Q () in Django

First example:

# ANDing Q objects q_object = Q() q_object.add(Q(), Q.AND) # ORing Q objects q_object = Q() q_object.add(Q(), Q.OR) 

Second example:

 >>> import operator # create a list of Q objects >>> mylist = [Q(question__contains='dinner'), Q(question__contains='meal')] # OR >>> Poll.objects.filter(reduce(operator.or_, mylist)) [<Poll: what shall I make for dinner>, <Poll: what is your favourite meal?>] # AND >>> Poll.objects.filter(reduce(operator.and_, mylist)) [] 

This method can be very useful for creating queries for pages with conditional filters, for example, on eBay.

But this, as I know, is not documented, so what are the best practices for this issue that will not be removed from support and will not confuse people who will read my code?

ps
And also - is this a good solution for using the "&" operator with Q () objects? In Django docs, I haven't found anything about this!

+4
source share
2 answers

Mark a document
It is good to use & or operator.and_ to represent 'AND' or shorter:

 >>> mylist = [Q(question__contains='dinner'), Q(question__contains='meal')] # AND >>> Poll.objects.filter(reduce(operator.and_, mylist)) # could be >>> Poll.objects.filter(*mylist) 
+5
source

Using Q is a documented function and is a public Django API. This means that it is stable and will not disappear in accordance with the Django backward compatibility policy.

https://docs.djangoproject.com/en/dev/topics/db/queries/#complex-lookups-with-q-objects

0
source

All Articles