在 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 theQuerySet
will be annotated with the specified values.
关于python - Django View : Count specific value from model,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37274905/