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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With