Opened 9 years ago
Last modified 6 years ago
#26067 closed New feature
Orderable ArrayAgg and StringAgg — at Version 1
Reported by: | Floris den Hengst | Owned by: | |
---|---|---|---|
Component: | contrib.postgres | Version: | dev |
Severity: | Normal | Keywords: | ArrayAgg StringAgg ordering |
Cc: | Matthew Pava | Triage Stage: | Accepted |
Has patch: | yes | Needs documentation: | no |
Needs tests: | no | Patch needs improvement: | yes |
Easy pickings: | no | UI/UX: | no |
Description (last modified by )
The Postgres-specific ArrayAgg and StringAgg aggregations were added in Django 1.9.
The documentation of Postgres 9.0 first mentions the possibility of ordering the results within aggregations such as ARRAY_AGG and STRING_AGG.
This could be useful in some cases.
For example: it could make sense to perform a StringAgg in lexicographical order in some cases.
The basic format of ordering within aggregations in SQL is quite simple:
SELECT ARRAY_AGG(some_field ORDER BY some_field ASC) FROM table; SELECT ARRAY_AGG(some_field ORDER BY some_field DESC) FROM table; SELECT ARRAY_AGG(some_field ORDER BY other_field ASC) FROM table;
It would be nice if the above would be supported as follows:
Model.objects.aggregate(ArrayAgg(some_field, order_by='some_field')) Model.objects.aggregate(ArrayAgg(some_field, order_by='-some_field')) Model.objects.aggregate(ArrayAgg(some_field, order_by='other_field'))
where order_by is an optional parameter. If it not specified, behavior can remain unchanged from the current implementation.
As noted by Josh Smeaton in the mailinglist discussion for this feature, any ordering added within may need to be contributed to GROUP BY. This might require some investigation.