gpt4 book ai didi

嵌套有reduce的django Q对象

转载 作者:行者123 更新时间:2023-12-05 08:23:35 28 4
gpt4 key购买 nike

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

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)

但现在我需要一些或:

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

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

最佳答案

无需使用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)]))

关于嵌套有reduce的django Q对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39394069/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com