I am trying to sum Django query with a condition. Suppose I have got some data like this:
JavaScript
x
15
15
1
| Name | Type |
2
---------------
3
| a | x |
4
| b | z |
5
| c | x |
6
| d | x |
7
| e | y |
8
| f | x |
9
| g | x |
10
| h | y |
11
| i | x |
12
| j | x |
13
| k | x |
14
| l | x |
15
And these types are string and they have values, like x = 1, y = 25, z = -3
How can I sum up all the values without a loop? Currently using a loop.
JavaScript
1
7
1
data = A.objects.all()
2
sum = 0
3
mapp = {'x': 1, 'y': 25, 'z': -3}
4
for datum in list(data):
5
sum = sum + mapp[datum.type]
6
print(sum)
7
Advertisement
Answer
To perform the calculation inside the database use Queryset.aggregate()
with an aggregate expression that uses Case
/When
:
JavaScript
1
12
12
1
from django.db.models import Sum, Case, When
2
3
A.objects.all().aggregate(
4
amount=Sum(Case(
5
When(type="x", then=1),
6
When(type="y", then=25),
7
When(type="z", then=-3),
8
default=0,
9
output_field=FloatField()
10
))
11
)
12