django用Q对象构建一个查询集 [英] django Building a queryset with Q objects

查看:194
本文介绍了django用Q对象构建一个查询集的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个表格,可让您选择多种项目类型以进行过滤.例如,假设您具有项目类型"Research","Training"和"Evaluation".

基本上,我要使用Q对象构建查询集:

projects.filter(Q(type__type="Research") | Q(type__type="Training"))

我不确定在没有filter()输入为字符串的情况下如何构建它,这会产生错误:

querystring = ""
for t in types:
    querystring += " | Q(type__type="+t+")"
projects.filter(querystring) ## produces error: "ValueError: too many values to unpack"

那么遍历类型以创建具有Q对象的查询集的方法是什么?

解决方案

您正在构建的字符串与实际的Q()查询对象无关.从第一个Q()实例开始并添加更多:

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

您还可以使用 functools.reduce()函数做到这一点:

from functools import reduce
from operator import or_

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

reduce()调用与上面的for循环完全相同;取一系列Q(..)对象,并将它们组合成一个更大的查询,并将所有部分与|或操作组合在一起.

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 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.

这篇关于django用Q对象构建一个查询集的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆