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

Django中如何使用aggregate聚合两模型求和并在HTML展示

问题原因

aggregate() 聚合方法的返回值是字典结构,格式为 {'total': 计算结果}。你当前代码将两个聚合返回的字典直接组成元组赋值给Total1,模板渲染时拿到的是包含两个字典的元组,自然无法得到正确的求和结果。

修复步骤
  • 分别执行两个模型的聚合查询,从返回的字典中取出total对应的数值
  • 对空查询结果做默认值0的兼容处理,避免无匹配数据时出现None参与加法运算的报错
  • 将两个数值相加后的结果赋值给上下文变量Total1
修正后的代码
def get_context_data(self, **kwargs):
    # 调用父类方法获取基础上下文
    context = super().get_context_data(**kwargs)
    today = datetime.datetime.now()
    
    context['expense1'] = Tracker.objects.filter(user=self.request.user)

    # 计算Body模型当月金额汇总
    body_agg = Body.objects.filter(
        user=self.request.user,
        pub_date__year=today.year,
        pub_date__month=today.month
    ).aggregate(total=Sum(F('price') * F('quantity')))
    body_total = body_agg['total'] if body_agg['total'] is not None else 0

    # 计算Sport模型当月金额汇总
    sport_agg = Sport.objects.filter(
        user=self.request.user,
        pub_date__year=today.year,
        pub_date__month=today.month
    ).aggregate(total=Sum(F('price') * F('quantity')))
    sport_total = sport_agg['total'] if sport_agg['total'] is not None else 0

    # 求和后传入上下文
    context['Total1'] = body_total + sport_total

    return context
模板渲染

原有模板写法无需额外调整,即可正常展示合计值:

Total: {{ Total1 }}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.27 01:27:26