【发布时间】:2018-06-01 09:01:57
【问题描述】:
我有两个模型“ModelParent”和“ModelChild”,其中“ModelParent”有很多“ModelChild”,这是我的模型结构:
class ModelParent(models.Model):
... some params ...
class ModelChild(models.Model):
TYPES = (
(1, 'First'),
(2, 'Second'),
)
parent = models.ForeignKey(ModelParent, on_delete=models.CASCADE, related_name='childs')
type = models.SmallIntegerField(choices=TYPES, default=0)
目前,数据库中只有一个 'ModelChild' 属于当前数据库中唯一的 'ModelParent','ModelChild' 的 'type' 值等于 '1',我得到的是 ' ModelParent' 对象,我需要将类型为 '1' 的他的 'childs' 的计数以及类型为 '2' 的他的 'childs' 的计数聚合到它,这就是我试图这样做的方式:
queryset = ModelParent.objects \
.annotate(first_count=Count('childs', filter=Q(childs__type=1))) \
.annotate(second_count=Count('childs', filter=Q(childs__type=2))).get(pk=1)
查询不会引发任何错误,但在查看响应时,两个注释的值都是“1”,而“first_count”应该是“1”,“second_count”应该是“0”。
我还注意到,无论我在过滤器“filter=Q(childs__type=1)”中为 'childs__type' 设置什么值,结果总是相同的,我可以这样设置,例如:'childs__type =10' 并且计数仍然等于 '1'.. 就像整个 'filter' 参数被忽略了。
【问题讨论】:
标签: python django django-models