2

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?

Yevhen Kuzmovych
  • 10,940
  • 7
  • 28
  • 48
Krishna
  • 33
  • 3
  • 1
    can you share `models.py` – Hemal Patel Jan 12 '23 at 05:23
  • class Task(models.Model): name = models.CharField(max_length=1000,default="",null=False) status = models.CharField(max_length=30,default="",null=False) pid = models.ForeignKey(Projects,on_delete=CASCADE) – Krishna Jan 12 '23 at 07:25
  • but hows is this possible with same `Project id` but different `status`? One project can have one status right? – Hemal Patel Jan 12 '23 at 07:59
  • annotate with condition could help: https://stackoverflow.com/questions/30752268/how-to-filter-objects-for-count-annotation-in-django – Razenstein Jan 12 '23 at 08:23

2 Answers2

3

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.

ruddra
  • 50,746
  • 7
  • 78
  • 101
1

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

Thanks you

Krishna
  • 33
  • 3