如何在Django中用group by乘和求和两列 [英] How multiply and sum two columns with group by in django

查看:47
本文介绍了如何在Django中用group by乘和求和两列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在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

如何使用您的Django ORM执行此操作?我试过了:

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'))

但是它不起作用,我得到的错误是TOTAL不在模型中.我该如何解决?

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

推荐答案

您可以执行以下操作:

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

注意:我假设 color 和其他字段一样是 Triangle 模型的字段.

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

这篇关于如何在Django中用group by乘和求和两列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆