#28296: Add support for aggregation through subqueries
-------------------------------------+-------------------------------------
Reporter: László Károlyi | Owner: nobody
Type: New feature | Status: new
Component: Database layer | Version: master
(models, ORM) |
Severity: Normal | Resolution:
Keywords: | Triage Stage: Accepted
Has patch: 0 | Needs documentation: 0
Needs tests: 0 | Patch needs improvement: 0
Easy pickings: 0 | UI/UX: 0
-------------------------------------+-------------------------------------
Comment (by Simon Charette):
Another API alternative could be allow queries to be passed directly to
aggregation functions
{{{#!python
# Implicit Count(*)
Performance.objects.annotate(
reserved_seats=Count(SeatReservation.objects.filter(
performance=OuterRef('pk'),
status__in=TAKEN_TYPES,
))
)
# Explicit Count('pk')
Performance.objects.annotate(
reserved_seats=Count(SeatReservation.objects.filter(
performance=OuterRef('pk'),
status__in=TAKEN_TYPES,
).values('pk'))
)
# Sum('seat__amount')
Performance.objects.annotate(
reserved_seats_total_amount=Sum(SeatReservation.objects.filter(
performance=OuterRef('pk'),
status__in=TAKEN_TYPES,
).values('seat__amount')
)
}}}
Or to allow passing a `subquery` kwarg to aggregation expressions. It can
either be `True` or a query
{{{#!python
# subquery=True
Performance.objects.annotate(
reserved_seats=Count(
'seat_reservations',
filter=Q(status__in=TAKEN_TYPES),
subquery=True,
),
)
# explicit subquery
Performance.objects.annotate(
reserved_seats=Count(
'seat_reservations',
subquery=SeatReservation.objects.filter(
status__in=TAKEN_TYPES,
),
),
)
# Sum('seat_reservations__seat__amount')
Performance.objects.annotate(
reserved_seats_total_amount=Sum(
'seat_reservations__seat__amount'',
subquery=True,
),
)
}}}
I think I like the`subquery` kwarg alternative better. It blends
naturally with the newly added `filter` kwarg and result in less verbose
expressions as the `subquery` shouldn't have to be provided most of the
time.
--
Ticket URL: <https://code.djangoproject.com/ticket/28296#comment:11>
Django <https://code.djangoproject.com/>
The Web framework for perfectionists with deadlines.
--
You received this message because you are subscribed to the Google Groups
"Django updates" group.
To unsubscribe from this group and stop receiving emails from it, send an email
to [email protected].
To post to this group, send email to [email protected].
To view this discussion on the web visit
https://groups.google.com/d/msgid/django-updates/065.59b24de8741c893d2a4146e4aebee6b9%40djangoproject.com.
For more options, visit https://groups.google.com/d/optout.