Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

django count per column

I have a ORM like this

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)                          

Imagine I have the following entries

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

What is the django ORM query that I have to make in order to get a queryset somewhat like the following

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

I started with the following but I don't know how to "merge" the two columns:

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

The goal of all this to get a table where I can show something like the following:

Name | completed | failed
foo  | 2         | 1
bar  | 1         | 0
like image 922
ezdazuzena Avatar asked Aug 26 '26 22:08

ezdazuzena


1 Answers

This should work as expected:

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()
        )
    )
)
like image 142
Borut Avatar answered Aug 29 '26 11:08

Borut



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!