[Solved]-How multiply and sum two columns with group by in django

14👍

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.

👤alecxe

Leave a comment