Python 返回来自同一模型的行数和总和
很抱歉标题不清楚…我不知道该怎么说。基本上,我有以下模型:Python 返回来自同一模型的行数和总和,python,django,django-models,Python,Django,Django Models,很抱歉标题不清楚…我不知道该怎么说。基本上,我有以下模型: class Items(models.Model): total=models.IntegerField() 现在的示例数据是: 1 10 2 15 3 90 6 10 9 20 我一共有5件物品,总共145件。我尝试了以下操作,但失败了,因为它正在对id列进行分组,该列返回以下结构
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')
你可以用Sum。只用 样本输出
{'total__sum': 145, 'id__count': 5}
{'total__sum': 145, 'id__count': 5}