Django报错:unsupported operand type(s) for +: 'int' and 'str'——使用aggregate(sum())聚合模型字段求和失败
Django aggregate(sum()) 报错:unsupported operand type(s) for +: 'int' and 'str' 解决方法
嘿,我一眼就揪出问题所在了!你现在误用了Python内置的sum()函数,但Django的聚合查询得用它专属的Sum聚合类,这俩完全不是一回事儿。
错误根源拆解
你写的这段代码:
cashsum= Payment.objects.filter(PaymentMethod="Cash").aggregate(sum('Amount'))
这里的sum是Python自带的求和函数,它会把传入的字符串'Amount'当成可迭代对象去遍历每个字符,尝试把这些字符串类型的字符和整数相加,自然就触发了unsupported operand type(s) for +: 'int' and 'str'这个错误。
正确解决步骤
- 导入Django的Sum聚合类
在你的views.py顶部加上这行代码:
from django.db.models import Sum
- 修正aggregate的写法
把原来的sum('Amount')换成Sum('Amount'),还可以给聚合结果起个清晰的别名,方便后续调用:
cashsum= Payment.objects.filter(PaymentMethod="Cash").aggregate(cash_total=Sum('Amount'))
这样cashsum会变成一个字典,键是cash_total,值就是求和后的金额结果,你可以通过cashsum['cash_total']直接获取这个值。
额外小建议
你的Payment模型里的Date字段用了CharField,其实更推荐用Django的DateField或者DateTimeField,这样后续做日期筛选、排序这类操作会方便很多,能避免不少字符串处理的麻烦。
内容的提问来源于stack exchange,提问作者MohZaf66
相关产品推荐
相关产品推荐

