gpt4 book ai didi

python - django 如何在单个字典中获取状态计数

转载 作者:行者123 更新时间:2023-12-04 10:05:27 24 4
gpt4 key购买 nike

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

最佳答案

您可以 use Count 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将是 QuerySetstatuscount领域。

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

关于python - django 如何在单个字典中获取状态计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61607816/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com