python - Django 查询明确列出字段值的计数

标签 python django count annotate

我有一个模型,其中有一个名为“state”的字段。它具有“已完成”、“进行中”、“失败”、“已创建”等值。我需要知道是否可以编写一个 django 查询,该查询将通过我提供一个类似的列表

{'completed': 2, 'in_progress': 5, 'failed': 0, 'created': 2}

表值

id | order_id | state
---------------------------
1  | 23       | completed
2  | 23       | completed
3  | 23       | in_progress
4  | 23       | created
5  | 23       | created
6  | 23       | in_progress
7  | 23       | in_progress
8  | 23       | in_progress
9  | 23       | in_progress

我尝试运行以下查询

order_items = OrderItems.objects.filter(order=order)
order_states = order_items.filter(
    state__in=['in_progress', 'completed', 'failed', 'created']
).values('state').annotate(Count('state'))

但它给了我一个像这样的列表

[{'state': u'completed', 'state__count': 8}, 
{'state': u'failed', 'state__count': 1}, 
{'state': u'in_progress', 'state__count': 1}]

最佳答案

这对你有用:-

from django.db.models import Count
StateStatusCount = order_items.objects.values('state').annotate(the_count=Count('state'))
print StateStatusCount

关于python - Django 查询明确列出字段值的计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42198558/

相关文章:

python - 如何阻止 CharField 在新的发布请求后清除其数据?

php - 单击元素时如何更新表格行+1?

python - 计算集合列表中的多次出现

mysql - 根据字段值标记表中的重复记录

python - 从带有富文本的 QLabel 中获取纯文本

python - 这是在 Pandas 中最快的分组方式吗?

python - 需要在 python 测试用例中模拟一些基类行为

python - imshow() 的图太小

django - 向 Django 选择字段添加一个新选择

python - "def __iter__(self): return iter(self.file)"是做什么用的?