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

2024-09-30 23:45:30 发布

您现在位置:Python中文网/ 问答频道 /正文

当我使用&;

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)

引擎盖下到底发生了什么?你知道吗


Tags: idobjects情况filterquerycountrymymodelamp
2条回答

对象定义魔法方法__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)

正确的答案是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'))>

相关问题 更多 >