Home > front end >  Partial sum based on the values of another field
Partial sum based on the values of another field

Time:08-03

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

CodePudding user response:

MyModel.objects.values('group').annotate(sum=Sum('value'))
  • Related