首页 > 解决方案 > 如何在 view.py 中对查询集的值求和

问题描述

这是我的view.py:

class PaymentControlList(ListView):
    template_name = "any.html"
    model = Payment

    def get_context_data(self, **kwargs):

        context = super().get_context_data(**kwargs)
        context['filter'] = PaymentFilter(self.request.GET, queryset=self.get_queryset())

        return context

在该模型(付款)中,我有一个名为 value 的字段,如何创建一个名为 total 的变量并在我的模板中使用它?那是我的 template.py

{% for item in filter.qs %}

    {% if item.entrada %}
    <tr>
        <th scope="row">{{ item.data }}</th>
        <td>{{ item.payment }}</td>
        <td>{{ item.type }}</td>
        <td class="item-value">{{ item.value }}</td>
    </tr>
    {% endif %}
{% endfor %}
<h3> {{ total }} </h3> <!--Sum of item.value

只是为了让你知道我已经使用 django-filter 编写了过滤器

标签: djangotemplatesfilterviewsum

解决方案


只需执行另一个查询来对值求和并将其添加到上下文中:

from django.db.models import Sum

class PaymentControlList(ListView):
    template_name = "any.html"
    model = Payment

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        queryset = self.get_queryset()
        filter = PaymentFilter(self.request.GET, queryset=queryset)
        context['filter'] = filter
        context['total'] = filter.qs.aggregate(Sum('value')).get('value__sum')

        return context

推荐阅读