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

2

7

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!

Mendelsohn answered 19/2, 2013 at 12:32 Comment(0)
S
10

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)
Secretarygeneral answered 19/2, 2013 at 13:5 Comment(1)
from functools import reduce reduce was moved into functoolsNones
B
0

Q usage is a documented feature and is a public Django API. That does mean it is stable and will not go away according to the Django backwards compatibility policy.

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

Betake answered 19/2, 2013 at 13:6 Comment(4)
I meant not usage of Q() in common, but usage of it in such specific waysMendelsohn
don't see what is special in your Q usage. You just use its public interface.Betake
In docs I dont see anything about "&" operator, and dynamic building of Q() query.Mendelsohn
it is documented in the very Q's docstring: > Encapsulates filters as objects that can then be combined logically (using & and |).Betake

© 2022 - 2024 — McMap. All rights reserved.