Django报错:unsupported operand type(s) for +: 'float' and 'NoneType' 求助
解决Django中float与NoneType相加的报错问题
核心原因
当指定日期范围内无匹配数据时,aggregate(Sum(...))会返回None,直接与float类型值相加就会触发unsupported operand type(s) for +: 'float' and 'NoneType'错误。
简洁解决方法
方法1:数据库层用Coalesce转0
直接在聚合查询时将空结果转为0,无需后续手动判空,适合大量类似参数的场景:
from django.db.models import Sum, Value from django.db.models.functions import Coalesce # 聚合时自动将空结果设为0 cell = Celldetail.objects.filter(DatePur__range=[modified6, modified5]).aggregate( total=Coalesce(Sum('Cell_price'), Value(0)) )['total'] bms = BMSdetail.objects.filter(DatePur__range=[modified6, modified5]).aggregate( total=Coalesce(Sum('BMS_price'), Value(0)) )['total'] month6price = cell + bms
方法2:Python层面用or快速转0
无需额外导入模块,一行代码完成判空转0:
cell = Celldetail.objects.filter(DatePur__range=[modified6, modified5]).aggregate(Sum('Cell_price'))['Cell_price__sum'] or 0 bms = BMSdetail.objects.filter(DatePur__range=[modified6, modified5]).aggregate(Sum('BMS_price'))['BMS_price__sum'] or 0 month6price = cell + bms
说明
- 方法1在数据库查询阶段处理空值,返回值始终为数值类型,避免Python层面的类型判断,适合数据量大或需要统一处理的场景。
- 方法2语法简洁,纯Python操作,适合快速修改现有代码。
内容的提问来源于stack exchange,提问作者Rana Talha
相关产品推荐
相关产品推荐

