Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/289.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/83.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何在django中使用group by对两列进行乘法和求和_Python_Sql_Django_Django Models_Group By - Fatal编程技术网

Python 如何在django中使用group by对两列进行乘法和求和

Python 如何在django中使用group by对两列进行乘法和求和,python,sql,django,django-models,group-by,Python,Sql,Django,Django Models,Group By,我需要在Django中执行以下查询: SELECT sum(T.width * T.height) as amount FROM triangle T WHERE T.type = 'normal' GROUP BY S.color 我怎样才能用你的django ORM做到这一点? 我试过这个: Triangle.objects.filter(type='normal').\ extra(select={'total':'width*height'}).\

我需要在Django中执行以下查询:

SELECT sum(T.width * T.height) as amount
FROM triangle T
WHERE T.type = 'normal'
GROUP BY S.color
我怎样才能用你的django ORM做到这一点? 我试过这个:

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

但它不起作用,我得到的错误是模型中没有TOTAL。如何修复它?

以下是您可以执行的操作:

Triangle.objects.filter(type="normal").values('color').annotate(amount=Sum('id', field="width * height")
这将生成以下查询(为了可读性,我对其进行了简化):


注意:我假设
color
与其他字段一样是
Triangle
模型的一个字段。

这是一个未记录的功能吗。。。?我在Django文档聚合页面的任何地方都没有看到它@tufelkinder我用django已经有一段时间了,答案很久以前就贴出来了。在快速查看文档之后,我没有看到
字段
关键字被记录。很好,如果你能找到文档参考,我会很高兴的。谢谢我试图在Django 1.11上使用它,但是作为示例,
字段
参数没有计算,
金额
只是由
id
列的值填充。
SELECT color, sum(width * height) as amount
FROM triangle 
WHERE type = 'normal'
GROUP BY color