Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically build complex queries with Q() in Django [closed]

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 technique might be very useful, for building queries for pages with conditional-filters for example, like on eBay.

But this things, as I know - not documented, so what best practices are exist for this matter, which will not be dropped from support, and will not confuse people who will read my code?

ps
And also - is it good solution to use "&" operator with Q() objects? In Django-docs I found nothing about it!

like image 715
Gill Bates Avatar asked Feb 19 '13 12:02

Gill Bates


1 Answers

Check the doc
It's fine 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)
like image 66
okm Avatar answered Oct 03 '22 10:10

okm