You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Django视图中对日期范围查询返回的结果进行求和

解决方法

第一步:导入Django聚合函数

在文件顶部引入Sum方法:

from django.db.models import Sum

第二步:修改视图函数添加总和计算

在你拿到过滤后的listIncome查询集后,调用aggregate方法统计所有符合条件的amount总和,同时补充缺失的分页数据到上下文,修改后的完整代码如下:

def SearchIncomeRange(request):
    listIncome = Income.objects.all()
    searchForm = IncomeSearchForm(request.POST or None)
    if request.method == 'POST':
        listIncome = Income.objects.filter(
            description__icontains=searchForm['description'].value(),
            date__range=[
                searchForm['start_date'].value(),
                searchForm['end_date'].value()
            ]
        )
    else:
        searchForm = IncomeSearchForm()
    # 新增:计算符合条件的所有收入总和,无数据时默认返回0
    total_amount = listIncome.aggregate(sum_amount=Sum('amount'))['sum_amount'] or 0
    paginator = Paginator(listIncome, 5)
    page = request.GET.get('page')
    paged_income = paginator.get_page(page)
    context = {
        'searchForm': searchForm,
        'paged_income': paged_income, # 补充分页数据到上下文,模板可直接渲染列表
        'total_amount': total_amount # 总额传入上下文
    }
    return render(request, 'cashier/search_income_range.html', context)

使用说明

模板中可以直接通过{{ total_amount }}调用统计好的总额,该值是所有符合查询条件的记录总和,不受分页限制。如果需要统计单页的总额,可自行遍历paged_income累加即可。


内容的提问来源于stack exchange,提问作者apollos

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.05 16:54:03