使用聚合 API Djang

2024-04-20 06:40:24 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个从数据库聚合一些值的简单任务,但问题是我需要在另一个django应用程序中这样做。我需要合计成本,价格和平均每月,并显示在一个表中。你知道吗

我使用的是泛型ListView,所以我可以聚合这个,非常简单的例子。你知道吗

在视图.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>

我的问题是,我没有得到任何关于模板,所以我想知道如果我做了正确的事情,有没有更好的方法。你知道吗


Tags: djangofromimportprojectappmodelscontextprice
1条回答
网友
1楼 · 发布于 2024-04-20 06:40:24

在模板中,不要执行{{ total.price_aux }},而是执行以下操作:

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

price_aux是上下文中的键,price_aux__sum是聚合查询中的dict键。你知道吗

相关问题 更多 >