Posts

Showing posts with the label Django Models

Aggregation Of An Annotation In GROUP BY In Django

Answer : Update: Since Django 2.1, everything works out of the box. No workarounds needed and the produced query is correct. This is maybe a bit too late, but I have found the solution (tested with Django 1.11.1). The problem is, call to .values('publisher') , which is required to provide grouping, removes all annotations, that are not included in .values() fields param. And we can't include dbl_price to fields param, because it will add another GROUP BY statement. The solution in to make all aggregation, which requires annotated fields firstly, then call .values() and include that aggregations to fields param(this won't add GROUP BY , because they are aggregations). Then we should call .annotate() with ANY expression - this will make django add GROUP BY statement to SQL query using the only non-aggregation field in query - publisher . Title.objects .annotate(dbl_price=2*F('price')) .annotate(sum_of_prices=Sum('dbl_price')) ....