Skip to main content
 首页 » 编程设计

python之每列的 django 计数

2024年08月19日31emanlee

我有一个这样的 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() 
        ) 
    ) 
)