python - Django View : Count specific value from model

标签 python django django-views

在 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/

相关文章:

python - django ModelChoiceField从views.py设置查询集

python - PrettyPrint 缩进/换行每个级别

python - 使用cherry.py调用函数

python - 如何获取值为列表的分隔查询集?

python - + :'Decimal' 和 'Decimal' 不支持的操作数类型

python - Django 缓存 - 可以抢先完成吗?

python - 单元测试时未找到 Django Reverse

javascript - 使用 Ajax 驱动的进度条上传 Django 文件

python - 使用 while 循环计算百分比的怪癖

python - 是否可以从字符串制作 Django urlpatterns?