python - 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
返回错误的数字。为什么会这样?
解决方案
在 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()
推荐阅读
- windows - 在 Windows 10 的开始菜单中看不到 Anaconda 导航器
- apache-flink - 在 Flink 中的每个工作人员上设置 taskmanager.numberOfTaskSlots
- python - 在 python 中实现方差膨胀因子代码
- r - 如何在 R 中生成具有 90% 置信区间的回归函数的斜率?
- python - 无法将 json 列表转换为 DataFrame
- ios - ios中的缩略图关联?
- sql - 无法在 SQL 语句中使用参数
- c# - 使用 MongoDB c# 时出现错误 UpdateOne、ReplaceOne 和 DeleteMany
- php - WooCommerce 产品变体下拉列表的自定义 HTML
- linux - Bash 命令拒绝在后台运行 &