Django:.annotate返回意外结果

时间:2019-06-21 09:55:44

标签: python django

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

(
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的事情我不了解吗?

1 个答案:

答案 0 :(得分:2)

似乎以前我也遇到过同样的问题,但是我不确定这是否正是您的问题。尝试将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