当我使用和或&;
criteria1 = Q(id__gte=802, id__lte=1000)
criteria2 = Q(country_id__contains='UK')
我一直在使用:
q = Mymodel.objects.filter(criteria1 & criteria2)
但在这种特殊情况下,当我使用&;时,它总是输出一行。 (我还检查了printq.query(),查询结果很好)
但是,当我使用和而不是&;时。查询提供正确的输出
q = Mymodel.objects.filter(criteria1 and criteria2)
引擎盖下到底发生了什么?你知道吗
对象定义魔法方法
__or__
和__and__
。这些函数允许重写&
数学和|
操作。检查this document如果您想知道
and
和&
之间的区别,请参见this question这是Q object code。你可以找到下面的代码。你知道吗
正确的答案是
criteria1 & criteria2
。criteria1 and criteria2
使用标准的Python布尔逻辑,将被求值为criteria2
,而criteria1 & criteria2
使用重载的__and__
方法并构造正确的复合Q
对象:相关问题 更多 >
编程相关推荐