django - 如何在 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 编写了过滤器
解决方案
只需执行另一个查询来对值求和并将其添加到上下文中:
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
推荐阅读
- atom-editor - Atom - 从不同层次结构打开多文件夹项目
- sql - 我有一个符合统计的数据现在我想要一个符合我的数据库的数据
- java - Spring-boot + liquibase:复杂的数据操作/迁移/填充
- amazon-web-services - 将 Amazon SQS 用于接收相同消息的多个使用者
- javascript - 使用 MVC 检查至少一个自动生成 jquery 数据表复选框
- javascript - 类javascript画布中的线旋转
- javascript - Extjs 网格跨度和行跨度
- python - pd.to_datetime 上的未知字符串格式
- firebase - 拦截 firebase-functions 响应(中间件)
- java - 在 GET 请求中应用正则表达式过滤器使用 Java 代码,而不是 SQL