Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django - Group by and do ArrayAgg

Tags:

django

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?

like image 316
Альберт Александров Avatar asked Oct 19 '25 04:10

Альберт Александров


1 Answers

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')
like image 109
Willem Van Onsem Avatar answered Oct 21 '25 18:10

Willem Van Onsem



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!