对不清楚的标题感到抱歉......我不知道怎么说对了。基本上,我有以下模型:
class Items(models.Model):
total=models.IntegerField()
示例数据现在只是:
1 10
2 15
3 90
6 10
9 20
我共有5个项目共145个。我尝试了以下但是它失败了因为它将id列分组,它返回了以下结构中的字典:
{"total_items":1,"items_worth":10, "total_items":2,"items_worth":15}
我想要的是:
{"total_items":5, "total_worth":145}
在SQL中,没关系:
SELECT COUNT(id) as total_items,SUM(total) as total_worth
DJANGO补充说,
SELECT COUNT(id) as total_items,SUM(total) as total_worth FROM model GROUP BY id
这是我目前的Django查询:
data=Items.Objects.all().annotate(total_items=Count('id'),total_worth=Sum('total')).values('total_items','total_worth')
答案 0 :(得分:1)
你可以使用Sum。只需使用aggregation
from django.db.models import Count, Min, Sum, Avg
data = Items.objects.aggregate(Sum('total'), Count('id'))
示例输出
{'total__sum': 145, 'id__count': 5}