当特定分组依据没有行时,是否有可能使分组查询获得0计数

时间:2018-11-22 07:52:25

标签: django django-orm

例如:

我们有两个表

Note
--------------------
id | text | label_id
1  | abcs | 1
2  | accs | 2
3  | abts | 1
Label
---------
id | name
1  | pro
2  | foo
3  | bar

现在我想要的数据是

Label Name | Note Count
------------------------
pro        | 2
foo        | 1
bar        | 0

现在,如果我这样做: Note.objects.all().values('label__name').annotate(count=Count('id', distinct=True))

我不会得到第三行,即(bar,0)。有什么办法获取此信息?条件是必须在单个查询中完成,并且查询应该在Notes模型上,而不是从Label模型开始

1 个答案:

答案 0 :(得分:0)

尝试使用conditional aggregation

Note.objects.annotate(
    count=Count(Case(
       When(label__note_count__gt=0, then=F('id')),
       output_field=IntegerField()
    )).all()