首页 > 解决方案 > Django 模型中的 Q() 和两个条件的问题

问题描述

假设我有这些模型:

class X(models.Model):
    interface = models.OneToOneField('Interface', related_name='x')

class Y(models.Model):
    interface = models.OneToOneField('Interface', related_name='y')
    
    
class Interface(models.Model):
    CHOICE = (
        (0, 'this is x'),
        (1, 'this is y'),
    )

    owner_type = models.IntegerField(choices=CHOICE,)

现在,我想计算 Interface Objects没有 x 关系和 y 关系的计数。我用了这两种方式:

z =  Interface.objects.filter(x__isnull=True).filter(y__isnull=True).count()
# Get correct number of objects 
x =  Interface.objects.filter(Q(x__isnull=True)and Q(y__isnull=True)).count()
# Get wrong number of objects 

z返回正确的结果但x返回错误的数字。为什么会这样?

标签: pythondjangodjango-models

解决方案


在 python 中,and运算符与&(&) 不同。and是逻辑 AND 运算符,而&是位运算符。因此,当您编写Q(x__isnull=True) and Q(y__isnull=True)它时,它将为您提供第一个虚假值(如果有的话)或最后一个真实值。因此,在您的情况下,它给出了Q(y__isnull=True). 相反,您想使用&

x =  Interface.objects.filter(Q(x__isnull=True) & Q(y__isnull=True)).count()

推荐阅读