python - 每列的 django 计数

标签 python django django-models django-orm

我有一个这样的 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'}]

我从以下开始,但我不知道如何“合并”这两列:

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

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

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

最佳答案

这应该按预期工作:

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()
        )
    )
)

关于python - 每列的 django 计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47333886/

相关文章:

python - 如何在 django 的查询集中使用 If else

django - 使用 prefetch_related 仅获取关系的特定条目

python - 在查询字符串评估中使用 Q() 链接重构多个 if 条件 Python/Django

django - django为什么不考虑我的语言文件?

javascript - 内存中创建的 Zip 文件已损坏

python - Matplotlib 从 C++ 绘制多个图表

Django 模板对象类型

django-models - Django 管理员错误指出表单中缺少一个字段

python - 如何在 scipy.integrate.simps 或 numpy.trapz 之间做出选择?

python - 如何使用 DatetimeField 列在 Django 中获取过去 7 天内每小时的最后一个对象?