'Django - Group by and do ArrayAgg
I have a model:
class Deviation(models.Model):
deviation_number = models.SmallIntegerField()
day_of_calculation = models.SmallIntegerField()
And I'd like to group records of the model by day_of_calculation and get list of deviation_numbers:
deviations = Deviation.objects \
.values('day_of_calculation') \
.annotate(deviation_numbers=ArrayAgg('deviation_number'))
But Django incorrectly creates sql:
SELECT "deviation"."day_of_calculation", ARRAY_AGG("deviation"."deviation_number" ) AS "deviation_numbers" FROM "deviation" GROUP BY "deviation"."day_of_calculation", "deviation"."deviation_number"
Grouping by deviation_number should not happen.
What do I do wrong?
Solution 1:[1]
You should add a .order_by(…) clause [Django-doc] to force a GROUP BY on the fields listed in the .order_by(…), so:
Deviation.objects.values('day_of_calculation').annotate(
deviation_numbers=ArrayAgg('deviation_number')
).order_by('day_of_calculation')
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Willem Van Onsem |
