简体   繁体   English

Django 带有注释的选择查询

[英]Django Choice Queries with annotate

I am stucked in django annotate query.我被困在 django 注释查询中。

here is certain Model I have been working.这里是某些 Model 我一直在工作。

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).在项目model中,status是一个choice字段,有选项(uploaded,inprogress,inreview,completed)。

I'm posting the query here, maybe someone finds it helpful.我在这里发布查询,也许有人觉得它有帮助。 In an API, write the following query:在 API 中,编写以下查询:

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
    })

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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