django Building a queryset with Q objects

点点圈 提交于 2019-11-30 09:37:14

问题


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?


回答1:


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)
projects.filter(query)

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))
projects.filter(query)

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.



来源:https://stackoverflow.com/questions/20222457/django-building-a-queryset-with-q-objects

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!