操纵Q对象,动态添加新条件

时间:2014-07-17 09:21:25

标签: python django django-orm django-q

我有一个像这样的Q对象。

params = Q(salt_spray__iregex=keyword) | Q(special_function__iregex=keyword) | Q(comment__iregex=keyword)

这里当我根据这个过滤我的模型时,事情很好。

Model.objects.filter(params)

但我想做以下事情。

params = Q(salt_spray__iregex=keyword) | Q(special_function__iregex=keyword) | Q(comment__iregex=keyword)
if data.get('market'):
    params[project__market] = data['market'] # not sure about this step. 
Model.objects.filter(params)

解决方案后的代码

data = self.cleaned_data

keyword = data['keyword']
params = Q()
if keyword:
    params |= Q(salt_spray__iregex=keyword) | Q(special_function__iregex=keyword) | Q(comment__iregex=keyword) # Note OR Operator. 

if data['market']:
    params &= Q(project__market=data['market']) # Note here AND Operator 
innovations = Innovation.objects.filter(params)
return innovations

2 个答案:

答案 0 :(得分:1)

您需要使用|运算符 Q对象:

params = Q(salt_spray__iregex=keyword) | Q(special_function__iregex=keyword) | Q(comment__iregex=keyword)
if data.get('market'):
    params |= Q(project__market=data['market'])
Model.objects.filter(params)

或者像@rinti提到的那样使用operator.or_

答案 1 :(得分:0)

导入operator然后您就可以这样做:

params = []

# Add as much as you like to your list dynamically
params.append(Q(something))

Model.objects.filter(reduce(operator.or_, params))