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
Configuring So That Pip Install Can Work from Github
Matplotlib Legend Markers Only Once
Numpy: Find First Index of Value Fast
Split a List into Parts Based on a Set of Indexes in Python
What's the Best Way to Find the Inverse of Datetime.Isocalendar()
Changing Iteration Variable Inside for Loop in Python
How to Detect the Python Version at Runtime
How to Increment a Datetime by One Day
How to Understand Numpy Strides for Layman
Super() Raises "Typeerror: Must Be Type, Not Classobj" for New-Style Class
Extract a Page from a PDF as a Jpeg
How to Remove Anaconda from Windows Completely
Find Longest Repetitive Sequence in a String
Drawing Lines Between Two Plots in Matplotlib
Multiple Inputs and Outputs in Python Subprocess Communicate