Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How multiply and sum two columns with group by in django

I need to do the following query in Django:

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

How can I do this using your django ORM? I tried this:

Triangle.objects.filter(type='normal').\
                 extra(select={'total':'width*height'}).\
                 values('id', 'total').\
                 annotate(amount=Sum('total'))

but it does not work, the error I get is that TOTAL is not in the model. How can I fix it?

like image 442
rodrixd Avatar asked Aug 13 '13 21:08

rodrixd


1 Answers

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.

like image 91
alecxe Avatar answered Sep 27 '22 19:09

alecxe