Django视图获取当月各客户存款总额时遇QuerySet属性错误求解决
问题解决:Django获取当月每位客户存款总额列表
错误原因
你代码里的customers = Customer.objects.all()返回的是Customer对象的集合(QuerySet),不是单个客户实例,直接调用customers.account_number会抛出'QuerySet' object has no attribute 'account_number'错误。同时当前写法只能计算单个客户的存款,无法生成所有客户的当月存款总额列表。
解决方案
方法1:通过Customer模型关联聚合(推荐)
直接在Customer查询中,通过外键关联Deposit表,用annotate计算每个客户当月的存款总额:
from django.db.models import Sum, Q from datetime import datetime def create_account(request): current_date = datetime.now().date() # 筛选所有客户,并聚合其当月存款总额 customers_with_deposit = Customer.objects.annotate( deposited_this_month=Sum( 'deposit__deposit_amount', filter=Q(deposit__date__year=current_date.year, deposit__date__month=current_date.month), default=0 ) ) # 将结果传入模板,每个Customer对象会新增deposited_this_month属性 context = {'customers': customers_with_deposit} # 模板渲染逻辑...
方法2:从Deposit模型分组查询
如果只需要展示当月有存款记录的客户,可以从Deposit表出发,按客户维度分组聚合:
from django.db.models import Sum from datetime import datetime def create_account(request): current_date = datetime.now().date() # 按客户分组,计算当月存款总额 deposit_summary = Deposit.objects.filter( date__year=current_date.year, date__month=current_date.month ).values( 'customer__surname', 'customer__othernames', 'customer__account_number' ).annotate( deposited_this_month=Sum('deposit_amount') ).order_by('customer__surname') # deposit_summary为字典列表,每个元素包含客户信息和当月存款总额 context = {'deposit_summary': deposit_summary} # 模板渲染逻辑...
补充说明
- 方法1会返回所有Customer对象,当月无存款的客户
deposited_this_month值为0,适合需要展示全量客户的场景。 - 方法2仅返回当月有存款记录的客户,数据量更小,适合聚焦交易客户的场景。
- 注意提前导入对应的聚合函数和
Q对象(方法1需要)。
内容的提问来源于stack exchange,提问作者apollos
相关产品推荐
相关产品推荐

