目前,我有以下两个查询集:

(
Event.objects.filter(organizer=1)
.values('pk', 'organizer')
.annotate(
    sold_tickets=Count('attendees', filter=Q(attendees__canceled=False))
)
.order_by('organizer')
)


(
Event.objects.filter(organizer=1)
.values('pk', 'organizer')
.annotate(available_tickets=Coalesce(Sum('tickets__quantity'), 0))
.order_by('organizer')
)


结果是:

<EventQuerySet [{'pk': 6, 'organizer': 1, 'sold_tickets': 1}, {'pk': 1, 'organizer': 1, 'sold_tickets': 529}, {'pk': 5, 'organizer': 1, 'sold_tickets': 1}, {'pk': 4, 'organizer': 1, 'sold_tickets': 2}]>
<EventQuerySet [{'pk': 1, 'organizer': 1, 'available_tickets': 1721}, {'pk': 4, 'organizer': 1, 'available_tickets': 30}, {'pk': 5, 'organizer': 1, 'available_tickets': 10}, {'pk': 6, 'organizer': 1, 'available_tickets': 20}]>


现在我的想法是将这些结合起来。但是,我总是在查询中得到意外和错误的数字:

(
Event.objects.filter(organizer=1)
.values('pk', 'organizer')
.annotate(
    available_tickets=Coalesce(Sum('tickets__quantity'), 0),
    sold_tickets=Count('attendees', filter=Q(attendees__canceled=False))
)

.order_by('organizer')
)


结果在这里

<EventQuerySet [{'pk': 6, 'organizer': 1, 'available_tickets': 20, 'sold_tickets': 2}, {'pk': 1, 'organizer': 1, 'available_tickets': 1765746, 'sold_tickets': 2116}, {'pk': 5, 'organizer': 1, 'available_tickets': 10, 'sold_tickets': 1}, {'pk': 4, 'organizer': 1, 'available_tickets': 60, 'sold_tickets': 4}]>


关于.annotate的某些内容我不理解吗?

最佳答案

似乎以前我遇到过同样的问题,但是我不确定这是否完全是您的问题。尝试将distinct=True添加到您的annotate中,该代码应为:

.annotate(
    available_tickets=Coalesce(Sum('tickets__quantity'), 0)
).annotate(
    sold_tickets=Count('attendees', filter=Q(attendees__canceled=False), distinct=True)
)


或者您可以尝试添加.distinct(),如下所示:

.annotate(
    available_tickets=Coalesce(Sum('tickets__quantity'), 0),
    sold_tickets=Count('attendees', filter=Q(attendees__canceled=False))
).distinct('available_tickets','sold_tickets')


这是我找到解决方案的地方:https://docs.djangoproject.com/en/dev/topics/db/aggregation/#combining-multiple-aggregations

10-07 15:39