Django 1.11 Annotating a Subquery Aggregate

后端 未结 6 851
醉酒成梦
醉酒成梦 2020-11-28 04:22

This is a bleeding-edge feature that I\'m currently skewered upon and quickly bleeding out. I want to annotate a subquery-aggregate onto an existing queryset. Doing this bef

6条回答
  •  温柔的废话
    2020-11-28 04:52

    A solution which would work for any general aggregation could be implemented using Window classes from Django 2.0. I have added this to the Django tracker ticket as well.

    This allows the aggregation of annotated values by calculating the aggregate over partitions based on the outer query model (in the GROUP BY clause), then annotating that data to every row in the subquery queryset. The subquery can then use the aggregated data from the first row returned and ignore the other rows.

    Performance.objects.annotate(
        reserved_seats=Subquery(
            SeatReservation.objects.filter(
                performance=OuterRef(name='pk'),
                status__in=TAKEN_TYPES,
            ).annotate(
                reserved_seat_count=Window(
                    expression=Count('pk'),
                    partition_by=[F('performance')]
                ),
            ).values('reserved_seat_count')[:1],
            output_field=FloatField()
        )
    )
    

提交回复
热议问题