在 Django ORM 中使用 'and' 和使用 '&' 的区别

Difference between using 'and' and using '&' in Django ORM

当我使用 and&

时,我的查询显示不同的结果
criteria1 = Q(id__gte=802, id__lte=1000)
criteria2 = Q(country_id__contains='UK')

我一直在用:

q = Mymodel.objects.filter(criteria1 & criteria2)

但在这种特殊情况下,当我使用 & 时,它总是输出一行。 (我也查了print q.query(),查询出来没问题)

但是,当我使用 and 而不是 & 时。查询给出正确的输出

q = Mymodel.objects.filter(criteria1 and criteria2)

幕后究竟发生了什么?

正确的是criteria1 & criteria2criteria1 and criteria2 使用标准的 Python 布尔逻辑并将计算为 criteria2,而 criteria1 & criteria2 使用重载的 __and__ 方法并构造正确的复合 Q 对象:

In [1]: from django.db.models import Q                                                                                                                                                                                                                                                                                                                        

In [2]: criteria1 = Q(id__gte=802, id__lte=1000)                                                                                                                                                                                                                                                                                                              

In [3]: criteria2 = Q(country_id__contains='UK')                                                                                                                                                                                                                                                                                                              

In [4]: criteria1 & criteria2                                                                                                                                                                                                                                                                                                                                 
Out[4]: <Q: (AND: ('id__gte', 802), ('id__lte', 1000), ('country_id__contains', 'UK'))>

In [5]: criteria1 and criteria2                                                                                                                                                                                                                                                                                                                               
Out[5]: <Q: (AND: ('country_id__contains', 'UK'))>

Q 对象定义魔术方法 __or____and__。这些函数允许覆盖 & 数学和 | 运算。检查 this document

如果您想了解 and& 之间的区别,请参阅 this question

这是Q object code。您可以找到以下代码。

class Q(tree.Node):
    def __or__(self, other):
        return self._combine(other, self.OR)

    def __and__(self, other):
        return self._combine(other, self.AND)