我使用了来自this post的代码:
from django.db.models import Avg
from django.db.models import FloatField
query_set=testTable.objects.filter(location='TgR',\
part__in=['Q', 'F'],week_number__lte=38,week_number__gte=42).\
aggregate(col1_avg=Avg('col1'),col2_avg=Avg('col2'),col3_avg=Avg('col3'),\
Total= (Avg('col1',output_field=FloatField())+Avg('col2', output_field=FloatField())+Avg('col3', output_field=FloatField()))
)
但我只收到一条记录(应该是20条记录)。看起来django汇总了所有记录。
我想做的是使用django model执行此查询:
SELECT week_number, part, type, AVG(col1), AVG(col2), AVG(col3), ( AVG(col1) + AVG(col2) + AVG(col3) ) as Total
FROM table1
WHERE location = 'TgR'
AND week_number BETWEEN 38 AND 42
AND part IN ('Q', 'F')
GROUP BY week_number, part, type
答案 0 :(得分:1)
聚合应该基于所有对象返回数据。如果您想获取每行数据,则应使用annotate()
代替。