django Q对象用reduce嵌套

时间:2016-09-08 14:51:15

标签: django

查询非常复杂(请不要尝试解决示例 - 问题更复杂)

crit=[]
crit.append(Q(firstcond = name) | Q(firstcond__isnull = True)
crit.append(Q(secondcond = name) | Q(firstcond__isnull = True)

MyObject.objects.filter(reduce(operator.and_, crit))

这可以按预期工作:

WHERE (firstcond = name OR firstcond IS NULL) AND (secondcond = name OR secondcond IS NULL)

但现在我需要一些OR:

WHERE ((firstcond = name OR firstcond IS NULL) AND (secondcond = name OR \
secondcond IS NULL)) OR (third = value)

我无法添加第三个int暴击列表,因为operator.and_在reduce中。我必须在reduce之后添加operator._or,但是如何?

1 个答案:

答案 0 :(得分:3)

无需使用reduce

crit = (Q(firstcond = name) | Q(firstcond__isnull = True)) & (Q(secondcond = name) | Q(firstcond__isnull = True)) | Q(third = value)
MyObject.objects.filter(crit)

如果您出于某种原因需要reduce

MyObject.objects.filter(reduce(operator.and_, crit) | Q(third = value))

或者:

MyObject.objects.filter(reduce(operator.or_([reduce(operator.and_, crit), Q(third = value)]))