2017-02-09 78 views
0

我有一個簡單的任務,從數據庫中彙總一些值,但問題是我需要在另一個django應用程序中執行此操作。我需要彙總每月的成本,價格和平均值的總和,並將其顯示在表格中。使用聚合API Django

我使用通用ListView所以我可以聚合這個,這麼簡單的例子。

在views.py

我有:

from django.views.generic import ListView 
from django.db.models import Sum, Avg 

from projects_app.models import Project 


class ProjectStatisticsList(ListView): 
    model = Project 
    template_name = 'statistics_app/statistics_list.html' 

    def get_context_data(self, **kwargs): 
     context = super(ProjectStatisticsList, self).get_context_data(**kwargs) 
     context["price_aux"] = Project.objects.all().aggregate(Sum("price_aux")) 
     return context 

和模板,我有:

<tr> 
    <th class="align-left">{% trans 'Project income' %}</th> 
    <th class="align-left">{{ total.price_aux }}</th> 
</tr> 

我的問題是,我沒有得到的東西的模板,所以我不知道如果我做的是正確的事情,有沒有更好的方法。

回答

4

而不是做{{ total.price_aux }}在你的模板,這樣做:

<th class="align-left">{{ price_aux.price_aux__sum }}</th> 

price_aux是在上下文中的關鍵,而price_aux__sum是從聚合查詢字典的關鍵。

+0

是的,謝謝,這是問題,我錯誤地解釋了字典鍵 – PetarP