简体   繁体   中英

Django Choice Queries with annotate

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?

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

I have done a similar task in my project, where I have to count the total completed and in progress projects. In my case, the scenario is, every project have a status. In the project model, status is a choice field which have choices (uploaded, inprogress, inreview, and completed).

I'm posting the query here, maybe someone finds it helpful. In an API, write the following query:

from django.db.models import Count, Q

 project_counts = Project.objects.filter(user=self.request.user).aggregate(
        total=Count('id'),
        inprogress=Count('id', Q(status=Project.ProjectStatus.IN_PROGRESS)),
        completed=Count('id', Q(status=Project.ProjectStatus.COMPLETED)))

and then return the response like this.

return response.Response({
        'total': project_counts['total'] | 0,
        'inprogress': project_counts['inprogress'] | 0,
        'completed': project_counts['completed'] | 0
    })

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM