Django orm count只返回一个结果

时间:2016-03-02 23:19:35

标签: django django-models django-orm

我有一个名为Orders的表,每个订单都有一个状态,我想根据状态计算结果:

status_counts = Order.objects.all( ).values( 'status' ).annotate(
    pending = Count( Case(
        When( status__exact = Order.STATUS_PENDING, then = F( 'pk' ) )
    ) ),
    completed = Count( Case(
        When( status__exact = Order.STATUS_COMPLETED, then = F( 'pk' ) )
    ) ),
    failed = Count( Case(
        When( status__exact = Order.STATUS_FAILED, then = F( 'pk' ) )
    ) ),
    reversed = Count( Case(
        When( status__exact = Order.STATUS_REVERSED, then = F( 'pk' ) )
    ) ) )

我的查询的问题是它返回每个状态的结果:

[{'completed': 4571, 'pending': 0, 'failed': 0, 'reversed': 0, 'status': 0}, {'completed': 0, 'pending': 2278, 'failed': 0, 'reversed': 0, 'status': 1}, {'completed': 0, 'pending': 0, 'failed': 0, 'reversed': 353, 'status': 3}]

我有没有办法得到这个结果:

{'completed': 4571, 'pending': 2278, 'failed': 0, 'reversed': 353, 'status': 0}

1 个答案:

答案 0 :(得分:0)

检查以下内容是否有效:

dict(Order.objects.all().values('status').annotate(scount=Count('status')).values_list('status', 'scount'))

分解

# get all available statuses
qs = Order.objects.all().values('status')

# annotate each status with count
qs = qs.annotate(scount=Count('status'))
# [{'status': 'completed', 'scount': 4571}, {'status': 'pending', 'scount': 2278} ...]

# now get only what you want in `values_list`
qs = qs.values_list('status', 'scount')
# [('completed', 4571), ('pending', 2278), ...]

# and then convert it to dict
result = dict(qs)
# {'completed': 4571, 'pending': 2278, ...}