Django annotate(),Count()

i get the output like this using annotate() and Count()

<QuerySet [{'pid': 11, 'status': 'Completed', 'status__count': 3}, {'pid': 11, 'status': 'Hold', 'status__count': 12}, {'pid': 11, 'status': 'InProgress', 'status__count': 2}, {'pid': 11, 'status': 'New', 'status__count': 3}, }]

this is code i write to get like this ** view.py**

tasks = Task.objects.values('pid','status').annotate(Count('status')).order_by('pid')

Actuallt i want my output like this

** <QuerySet [{'pid': 11, 'Completed': 3, 'Hold': 12, 'InProgress': 2,'New': 3},}] **

How can i do?

You can try like this:

Task.objects.values('pid').annotate(
    completed = Count('status', filter=Q(status='Completed')),
    hold=Count('status', filter=Q(status="Hold")),
    in_progress=Count('status', filter=Q(status="InProgress"))
).order_by('pid')

More information can be found in documentation.

An another method i found this also worked enter image description here

Thanks you

Back to Top