每列的 django 计数

django count per column

我有这样的 ORM

from django.db import models,

class MyObject(models.Model):

   class Meta:
       db_table = 'myobject'

   id = models.IntegerField(primary_key=True)
   name = models.CharField(max_length=48)                                        
   status = models.CharField(max_length=48)                          

假设我有以下条目

1 | foo | completed
2 | foo | completed
3 | bar | completed
4 | foo | failed

为了获得类似于以下的查询集,我必须进行什么 django ORM 查询

[{'name': 'foo', 'status_count': 'completed: 2, failed: 1'},
 {'name': 'bar', 'status_count': 'completed: 1'}]

我从以下开始,但我不知道如何 "merge" 这两列:

from django.db.models import Count
models.MyObject.objects.values(
    'name',
    'status'
).annotate(my_count=Count('id'))

所有这一切的目标是获得一个 table,我可以在其中展示如下内容:

Name | completed | failed
foo  | 2         | 1
bar  | 1         | 0

您需要在查询末尾添加 "order_by" 以将相似的项目组合在一起。

像这样的东西应该可以工作:

from django.db.models import Count
models.MyObject.objects.values(
    'name',
    'status'
).annotate(my_count=Count('id')).order_by()

详情见https://docs.djangoproject.com/en/1.11/topics/db/aggregation/#interaction-with-default-ordering-or-order-by

编辑:抱歉,我意识到这并没有回答有关合并列的问题...我认为您实际上无法在单个查询中完成此操作,尽管您随后可以很容易地遍历结果并使你的输出 table.

这应该按预期工作:

test = MyObject.objects.values('name').annotate(
    total_completed=Count(
        Case(
            When(
                status='completed', then=1), output_field=DecimalField()
        )
    ),
    total_failed=Count(
        Case(
            When(status='failed', then=1), output_field=DecimalField()
        )
    )
)