by rahimnathwani · 4y ago · 0 comments
How would we do this in an ORM like ActiveRecord or Django ORM, without generating multiple queries?
Edit: I think it's something like
Album
.select(:id, :name, "SUM(songs.length) AS total_length")
.left_outer_joins(:songs)
.group(:id)
.order("SUM(songs.length) ASC")
I think you don't even need to explicitly wrap it in Arel.Also, for anyone reading, a total_length method dynamically will be added objects returned. :)
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).