如何在Django中用group by乘和求和两列

编程入门 行业动态 更新时间:2024-10-28 12:29:51
本文介绍了如何在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乘和求和两列

本文发布于:2023-11-22 04:21:50,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1615959.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:中用   如何在   Django   group

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!