3 ms·
In Django, you would write an annotation as documented at https://docs.djangoproject.com/en/4.1/topics/db/aggregation/#generating-aggregates-for-each-item-in-a-
by ColonelPhantom 4y ago
In Django, you would write an annotation as documented at https://docs.djangoproject.com/en/4.1/topics/db/aggregation/#generating-aggregates-for-each-item-in-a-queryset https://docs.djangoproject.com/en/4.1/topics/db/aggregation/...
So something like
Album.objects.annotate(duration=Sum('track__length')).order_by('duration')
There are also libraries that enable you to define an annotation or aggregation inside a model, that you can then get with a call like select_properties, similar to the built-in select_related (which you use to get a foreign key in one query) and prefetch_related (which is select_related for many-to-many fields).
- rahimnathwani 4y agoThanks. I haven't used Django for ages, but do recall using annotate() in the past. At that time, I didn't need to worry about performance, so didn't look into what happens under the hood, i.e. whether the call generates more than one SQL query.