Skip to content
Advertisement

How to sum with condition in a Django queryset

I am trying to sum Django query with a condition. Suppose I have got some data like this:

JavaScript

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

Advertisement

Answer

To perform the calculation inside the database use Queryset.aggregate() with an aggregate expression that uses Case/When:

JavaScript
Advertisement