gpt4 book ai didi

python - Django View : Count specific value from model

转载 作者:行者123 更新时间:2023-12-01 03:57:02 25 4
gpt4 key购买 nike

在 django View 中我有:

 signed_by = Demographic.objects.all().values_list('data_entered_by')

我得到[(u'Patient',),(u'Patient',),(u'Other',)]

我想分别计算所有具有 Patient 值和所有具有 Other 值的值。

如果我使用

signed_by.count() 

我得到了所有人的计数。如何计算指定值?

最佳答案

您可以annotate查询集:

signed_by = Demographic.objects.values('data_entered_by').annotate(cnt=Count('id'))

因此,您可以按如下方式获取每个 data_entered_by 值的计数,因为它返回一个 dict 对象列表:

for q in signed_by:
print(q['data_entered_by'], q['cnt])
<小时/>

来自文档:

When an annotate() clause is specified, each object in the QuerySet will be annotated with the specified values.

关于python - Django View : Count specific value from model,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37274905/

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