使用OuterRef进行查询

时间:2019-06-21 11:32:02

标签: python django

虽然结果是预期的结果,但是感觉就像我使用了很多嵌套。特别是我使用Ticket而不是Event来使用total_outstanding_revenue。我想知道您是否有更好和更短的方法来编写该查询?

我的查询集给我以下结果:

total_outstanding_revenue:
<QuerySet [{'event__pk': 4, 'total_outstanding_revenue': 56000}, {'event__pk': 5, 'total_outstanding_revenue': 9000}, {'event__pk': 6, 'total_outstanding_revenue': 29000}]>

这是我的查询集:

outstanding_revenue = (
    Ticket.objects.filter(pk=OuterRef('pk'))
    .annotate(
        sold_tickets=Count(
            'attendees',
            filter=Q(
                attendees__canceled=False,
                attendees__order__status__in=(
                    OrderStatus.PAID, OrderStatus.PENDING, OrderStatus.PARTIALLY_REFUNDED, OrderStatus.FREE
                ),
            ),
        )
    )
    .annotate(
        available_tickets=ExpressionWrapper(
            F('quantity') - F('sold_tickets'), output_field=IntegerField()
        )
    )
    .annotate(
        outstanding_revenue=ExpressionWrapper(
            F('available_tickets') * F('price_gross'), output_field=IntegerField()
        )
    )
    .values('outstanding_revenue')
)

total_outstanding_revenue = Ticket.objects.filter(event__organizer=1, event__status=EventStatus.LIVE).annotate(
    outstanding_revenue=Subquery(outstanding_revenue)).values(
    'event__pk'
).annotate(total_outstanding_revenue=Sum('outstanding_revenue', output_field=IntegerField())).values(
    'event__pk', 'total_outstanding_revenue'
).order_by()

0 个答案:

没有答案