Django Aggregation: Summation of Multiplication of Two Fields

Django Aggregation: Summation of Multiplication of two fields

Update: for Django >= 1.8 please follow the answer provided by @kmmbvnr

it's possible using Django ORM:

here's what you should do:

from django.db.models import Sum

total = ( Task.objects
.filter(your-filter-here)
.aggregate(
total=Sum('progress', field="progress*estimated_days")
)['total']
)

Note: if the two fields are of different types, say integer & float, the type you want to return should be passed as the first parameter of Sum

It's a late answer, but I guess it'll help someone looking for the same.

How multiply and sum two columns with group by in django

Here's what you can do:

Triangle.objects.filter(type="normal").values('color').annotate(amount=Sum('id', field="width * height")

This will produce the following query (I've simplified for readability):

SELECT color, sum(width * height) as amount
FROM triangle
WHERE type = 'normal'
GROUP BY color

Note: I've assumed color is a field of Triangle model as other fields.

Sum Product using Django ORM

Try something like this

from django.db.models import Sum, F
MyModel.objects.filter(<filters>).aggregate(sum=Sum(F('field1')*F('field2')))["sum"]


Related Topics



Leave a reply



Submit