[Fixed]-Django Building a queryset with Q objects


You are just building a string with no relationship to actual Q() query objects; start with the first Q() instance and add more:

query = Q(type__type=types[0])
for t in types[1:]:
    query |= Q(type__type=t)

You could also use the functools.reduce() function to do this:

from functools import reduce
from operator import or_

query = reduce(or_, (Q(type__type=t) for t in types))

The reduce() call does exactly the same thing as the for loop above; take a series of Q(..) objects and combine them into a larger query with all the parts combined with | or operations.

Leave a comment