Partial sum based on the values of another field

Question:

Given a model like this (example for the purpose of generalization):

Group Value
1 2
1 5
1 64
2 1
2 4

How could I make a sum for each group and obtain the results for the sum of each group instead of the total sum of all the groups?

Until now I had done sums like this:

total_value = myModel.objects.aggregate(sum=Sum('value'))

The result would be: 2 + 5 + 64 + 1 + 4 = 76

Expected result (list or dict if possible):

Group 1: 71
Group 2: 5
Asked By: Cheknov

||

Answers:

MyModel.objects.values('group').annotate(sum=Sum('value'))
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.