I have a form that allows you to pick multiple project types to filter from. For instance, say you have the project types "Research", "Training", and "Evaluation".
Basically what I'm looking to do is build a queryset using Q objects like:
projects.filter(Q(type__type="Research") | Q(type__type="Training"))
I'm just not sure how to build this without the filter() input being a string, which produces an error:
querystring = ""
for t in types:
querystring += " | Q(type__type="+t+")"
projects.filter(querystring) ## produces error: "ValueError: too many values to unpack"
So what would be a way to iterate over the types to create a queryset with Q objects?
You are just building a string with no relationship to actual
Q()
query objects; start with the firstQ()
instance and add more:You could also use the
functools.reduce()
function to do this:The
reduce()
call does exactly the same thing as thefor
loop above; take a series ofQ(..)
objects and combine them into a larger query with all the parts combined with|
or operations.