Django查询清楚地列出字段值的计数

时间:2017-02-13 07:21:47

标签: python django count annotate

我有一个名为'state'的模型。它具有'completed','in_progress','failed','created'等值。我需要知道我是否可以编写一个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}]

3 个答案:

答案 0 :(得分:1)

伙计们,我刚刚发现了自己。由于我的django版本已经过时,我使用的是aggregate_if,最好用conditional expressions编写。

from django.db.models import Q
from aggregate_if import Count, Sum

order_states = order_items.aggregate(
    created=Count('pk', only=Q(state=OrderItems.STATE_CREATED)),
    in_progress=Count('pk', only=Q(state=OrderItems.STATE_IN_PROGRESS)),
    complete=Count('pk', only=Q(state=OrderItems.STATE_COMPLETED)),
    failed=Count('pk', only=Q(state=OrderItems.STATE_FAILED))
)

其中

OrderItems.STATE_CREATED = 'created'
OrderItems.STATE_IN_PROGRESS = 'in_progress'
OrderItems.STATE_COMPLETED = 'completed'
OrderItems.STATE_FAILED = 'failed'

感谢@shahanar帮助我搞清楚这个

答案 1 :(得分:0)

这对你有用: -

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

答案 2 :(得分:0)

为了获得Fahim所需的字典结构,我们可以将Piyush的答案扩展到dict理解:

from django.db.models import Count
state_count = {i["state"]: i["count"] for i in order_items.objects.values('state').order_by().annotate(count=Count('state'))}
print(state_count)

此外,还需要order_by(),例如如果订单设置为模型的Meta类。有关优秀说明,请参阅Django equivalent of COUNT with GROUP BY