Sum记录Django中的值

时间:2010-05-13 16:07:18

标签: 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中解决此类聚合的最佳方法是什么?

3 个答案:

答案 0 :(得分:4)

Alexander的解决方案将为您提供正确的结果,但每个项目都有一个查询。使用 annotate在一个查询中执行整个操作。

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

答案 1 :(得分:2)

尝试使用aggregate

from django.db.models import Sum

for project in Projects.objects.all():
  print project, project.cost_set.all().aggregate(sum_of_cost=Sum('cost'))['sum_of_cost'] or 0

答案 2 :(得分:2)

这是一种方法。可能有一种更有效的方法来编写get_total_cost函数......但这应该可行。

型号:

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

    def get_total_cost(self):
        tot = 0
        for cost in Cost.objects.filter(project=self):
            tot += cost.cost
        return tot

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

查看:

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',{'projects',Project.objects.all()},context_instance=RequestContext(request))

模板:

{% for project in projects %}
<p>{{project.title}}: {{project.get_total_cost}}</p>
{% endfor %}

这是非常基本的东西。

花些时间浏览Django tutorialsdocumentation