Django orm count return 只有一个结果

Django orm count return only one result

我将这个 table 命名为 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' ) )
    ) ) )

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

[{'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}

检查以下是否有效:

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, ...}