我有一个像这样的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
答案 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))