A co-worker asked me the other day about the best way to OR together a list of Q objects in the Django ORM. Usually you have a specific number of conditions and you can use Q objects and the bitwise OR operator to logical OR the query conditions together. The Q object is necessary because multiple arguments or successive calls to .filter are ANDed. But what if you have an arbitrary number of Q conditions?
One suggestion is to use the undocumented .add method of the Q object in a loop to add multiple query conditions together. I thought this might be a good use case for reduce and the operator module:
# Normal Usage with the | operator from django.db.models import Q qs = MyModel.objects.filter(Q(cond1=1) | Q(cond2="Y")) #but given a list of Q conditions from operator import __or__ as OR lst = [Q(...), Q(...), Q(...)] qs = MyModel.objects.filter(reduce(OR, lst))
Is this the most Pythonic approach?