6đź‘Ť
âś…
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()
)
)
)
👤Borut
0đź‘Ť
You need to include an “order_by” on to the end of your query to group the like items together.
Something like this should work:
from django.db.models import Count
models.MyObject.objects.values(
'name',
'status'
).annotate(my_count=Count('id')).order_by()
See https://docs.djangoproject.com/en/1.11/topics/db/aggregation/#interaction-with-default-ordering-or-order-by for details.
EDIT: Sorry, I realize this doesn’t answer the question about merging the columns… I don’t think you can actually do it in a single query, although you can then loop through the results pretty easily and make your output table.
👤skulegirl
Source:stackexchange.com