Django如何在单个字典中获取状态计数

2024-04-23 06:50:55 发布

您现在位置:Python中文网/ 问答频道 /正文

In my user table i have many user type and status (pending = 0,1 = approved). i am getting the count like.

     user = {}
     user['pending'] = User.objects.filter(type=3,status='0').count()
     user['approved'] = User.objects.filter(type=3,status='2').count()
     user['blocked'] = User.objects.filter(type=3,status='4').count()
     print(user)

Using this i am getting result in this way like : {'pending': 0, 'approved': 1, 'blocked': 0} what actually i need is i want this same result through a single query can any one please help me related this ?? thanks in advance


Tags: objectstypestatuscountresultfilterthisam
1条回答
网友
1楼 · 发布于 2024-04-23 06:50:55

你可以use ^{} aggregation

from django.db.models import Count


result = User.objects.filter(type=3, status__in=[0, 2, 4]).values('status')
                    .order_by('status')
                    .annotate(count=Count('status'))

# create dict
result_dict = {r.status : r.count for r in result}

# rename keys of dict
new_keys= {'0':'pending', '2':'approved', '4':'blocked'}
result_with_new_keys = {new_keys[key] : value for key, value in result.items()}

result将是一个带有statuscount字段的QuerySet

然后,我们从QuerySet创建一个dict,然后重命名键以获得所需的字典

相关问题 更多 >