For the Q object in Django, I'd like to be able to parse AND
, OR
queries. Here is an example of a query to be parsed:
from django.db.models import Q
Poll.objects.filter(
Q(pub_date=date(2005, 5, 2)) | Q(pub_date=date(2005, 5, 6))
)
This query is identical:
a = Q(pub_date=date(2005, 5, 2))
b = Q(pub_date=date(2005, 5, 6))
Poll.objects.filter(
a | b
)
Is it possible to parse a query like the one below? It will obviously fail because join
returns a string concatenated with the character |
. But that is the Django ORM syntax needed, and we'd like to dynamically be able to parse these queries without hard coding the Q
arguments.
a = Q(pub_date=date(2005, 5, 2))
b = Q(pub_date=date(2005, 5, 6))
Poll.objects.filter(
" | ".join([a,b])
)
You should be able to compose that programatically by repeating the or operator:
q = Q()
for some_date in collection_of_dates:
q |= Q(pub_date=some_date)
Poll.objects.filter(q)