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 the code I write to get like this
view.py:
tasks = Task.objects.values('pid','status').annotate(Count('status')).order_by('pid')
Actually I want my output like this
<QuerySet [{'pid': 11, 'Completed': 3, 'Hold': 12, 'InProgress': 2,'New': 3},}]
How can I do it?
CodePudding user response:
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.