Cheknov
Cheknov

Reputation: 2082

Partial sum based on the values of another field

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

Upvotes: 0

Views: 37

Answers (1)

Waldemar Podsiadło
Waldemar Podsiadło

Reputation: 1412

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

Upvotes: 1

Related Questions