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

Django按月份分组展示交易数据及金额总和的实现咨询

按月份分组展示交易数据及当月总额的实现方案

一、优化视图函数

原视图多次查询数据库,效率较低,以下是优化后的实现,一次性完成数据分组和总额计算:

from django.db.models import Sum
from django.shortcuts import render

def alltrans(request):
    # 获取所有交易并按日期排序
    all_transactions = Daily.objects.order_by('transdate')
    
    # 构建月份分组数据:键为(年份, 月份),值包含交易列表和当月总额
    monthly_groups = {}
    for trans in all_transactions:
        month_key = (trans.transdate.year, trans.transdate.month)
        if month_key not in monthly_groups:
            monthly_groups[month_key] = {
                'transactions': [],
                'month_total': 0
            }
        monthly_groups[month_key]['transactions'].append(trans)
        monthly_groups[month_key]['month_total'] += trans.transamount
    
    # 按年份、月份顺序排序分组数据
    sorted_monthly_data = sorted(monthly_groups.items(), key=lambda x: x[0])
    
    # 计算全部交易总金额
    overall_total = Daily.objects.aggregate(total=Sum('transamount'))['total'] or 0
    
    context = {
        'monthly_data': sorted_monthly_data,
        'overall_total': overall_total,
        'title': 'All Trans',
    }
    return render(request, 'alltrans.html', context)

二、修改模板代码

调整模板,循环展示每个月份组的交易列表和当月总额:

{% for (year, month), group in monthly_data %}
    <h3>{{ year }}年{{ month }}月</h3>
    <table style="width: 100%">
        <tr>
            <th>ID</th>
            <th>日期</th>
            <th>详情</th>
            <th>分类</th>
            <th>支付方式</th>
            <th>子详情</th>
            <th>金额</th>
        </tr>
        {% for trans in group.transactions %}
        <tr>
            <td>{{ trans.transid }}</td>
            <td>{{ trans.transdate|date:"Y-m-d" }}</td>
            <td>{{ trans.transdetails }}</td>
            <td>{{ trans.transcategory }}</td>
            <td>{{ trans.transmode }}</td>
            <td>{{ trans.transsubdetails }}</td>
            <td>{{ trans.transamount }}</td>
        </tr>
        {% endfor %}
        <!-- 当月总额行 -->
        <tr style="font-weight: bold;">
            <td colspan="6" align="right">当月总额:</td>
            <td>{{ group.month_total }}</td>
        </tr>
    </table>
    <hr>
{% endfor %}

<!-- 全部交易总金额 -->
<h4>全部交易总金额: {{ overall_total }}</h4>

关键说明

  • 用(年份, 月份)作为分组键,避免跨年同月份的数据混淆
  • 视图中仅查询两次数据库,大幅提升性能
  • 模板通过date过滤器格式化日期,增强可读性
  • 当月总额用加粗样式突出,便于查看

内容的提问来源于stack exchange,提问作者Jamal A M

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 01:17:59