I would like to know in Django how to get the average number of grouped elements in my table per element (without using .extra(…) if possible).
Concretely I have a table (DwarvesEatingCakes) consisting of Dwarves and Cakes. Each pair (dwarf, cake) is unique. I want to get the average number of cakes eaten by each dwarf.
The following code does not seem to work:
avg_cakeeaten_dict = DwarvesEatingCakes.values('dwarf').annotate(num_cake=Count('cake')).aggregate(avg_cake_eaten=Avg('num_cake'))
Thanks for the help!
The answer I ended up using is the following (based on Rob’s answer):
Of course you also make your checks against divide by 0. There might be a standard way of doing this though since it is a relatively common place query.