Home > database >  Django Choice Queries with annotate
Django Choice Queries with annotate

Time:06-01

I am stucked in django annotate query.

here is certain Model I have been working.

class Claim(model.Model)
     CLAIMS_STATUS_CHOICES = (
    (2, PROCESSING),
    (1, ACCEPTED),
    (0, REJECTED)
) 
    status = models.CharField(max_length=10,choice=CLAIMS_STATUS_CHOICES)

problem is I don't want to annotate processing choice but I just want to get individual status count of accepted and rejected. Here is what I tried.

claim = Claim.objects.filter(Q(status=1) | Q(status=0))
total_status_count = claim.count()
status_counts = Claim.objects.filter(Q(status=1) |Q(status=0)).annotate(count=Count('status')).values('count', 'status')

but I am getting multiple rejected and accepted queries this is what I got as op

 [
        {
            "total_claims": 3,
            "status_count": [
                {
                    "status": "1",
                    "count": 1
                },
                {
                    "status": "0",
                    "count": 1
                },
                {
                    "status": "1",
                    "count": 1
                }
            ]
        }
    ]

what I wanted

 [
        {
            "total_claims": 3,
            "status_count": [
                {
                    "status": "1",
                    "count": 2
                },
                {
                    "status": "0",
                    "count": 1
                }
            ]
    }
]

Any help regarding this?

CodePudding user response:

Claim.objects.exclude(status=2).values('status').annotate(count=Count('status'))
  • Related