views:

62

answers:

2

How do I pass a list of Qs to filter for OR lookups? Something like:

q_list = [Q(xyz__isnull=True), Q(x__startswith='x')]?

Without a list I would do:

Model.objects.filter(Q(xyz__isnull=True) | Q(x__startswith='x'))
+3  A: 

Use python's reduce() function:

import operator
reduced_q = reduce(operator.or_, q_list)
Model.objects.filter(reduced_q)
bjunix
A: 

Q objects also have an add method which takes another Q object and a Q connector (either AND or OR).

q_object = Q(xyz__isnull=True)
q_object.add(Q(x__startswith='x'), Q.OR)

I've found this to be helpful when constructing OR filters and I've written a longer example on my blog: "Adding" Q objects in Django

Brad Montgomery