python - 求和 Django 中的记录值

标签 python django

我在我的应用中定义了几个模型:

class Project(models.Model):
    title   = models.CharField(max_length=150)
    url     = models.URLField()
    manager = models.ForeignKey(User)

class Cost(models.Model):
    project = models.ForeignKey(Project)
    cost    = models.FloatField()
    date    = models.DateField()

我想汇总每个项目的成本并呈现值view.py:

from mypm.costs.models import Project, Cost
from django.shortcuts import render_to_response
from django.db.models import Avg, Sum

def index(request):
    # ...
    return render_to_response('index.html',...

在 Django ORM 中解决此类聚合的最佳方法是什么?

最佳答案

Alexander 的解决方案将为您提供正确的结果,但每个项目都有一个查询。使用 注释在单个查询中完成所有事情。

from django.db.models import Sum

annotated_projects = Project.objects.all().annotate(cost_sum=Sum('cost__cost'))
for project in annotated_projects:
    print project.title, project.cost_sum

关于python - 求和 Django 中的记录值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2828343/

相关文章:

django - 使用 asyncio 的异步信号

python - 我不明白为什么这个 while 循环不能正常运行

Python 相对导入找不到包

python - 找不到文件错误 : [Errno 2] No such file or directory (python error)

Python 绘图轨迹密度

python - `my_instance = MyClass(a, b).my_method(c)` 是可接受的(Pythonic)模式吗?

python - 将数据保存到数据库时出错

python - DJango 包含不适用于 JSONField

python - 无法使用 DRF APIClient() 更改 header

python - 如何在 Django 1.7 迁移中引用生成的权限