Python将无转换为十进制

时间:2015-06-10 16:02:04

标签: python

如何在Python中将None对象转换为Decimal对象。

代码:

c['suspended_amount'] = sum([owned_license.charge_amount for owned_license in log.owned_licenses.all()])

错误:

TypeError: unsupported operand type(s) for +: 'decimal.Decimal' and 'NoneType'

2 个答案:

答案 0 :(得分:4)

跳过这些值:

c['suspended_amount'] = sum(owned_license.charge_amount
                            for owned_license in log.owned_licenses.all() 
                            if owned_license.charge_amount)

我删除了[..]方括号; sum()采用可迭代,我使用generator expression提供。使用方括号代替list comprehension,它将不必要地首先构建所有值的完整列表。 Sum只需要逐个获取值,它们不需要预先存在。

更好的是,要求数据库仅包含charge_amount不是NULL的那些行:

c['suspended_amount'] = sum(
    owned_license.charge_amount
    for owned_license in log.owned_licenses.exclude(charge_amount__isnull=True).all())

最好的,请让数据库为你做总结:

from django.db.models import Sum

c['suspended_amount'] = (
    log.owned_licenses.exclude(charge_amount__isnull=True)
        .aggregate(Sum('charge_amount'))['charge_amount__sum'])

请参阅Aggregation documentation

答案 1 :(得分:2)

您也可以使用'或'操作者:

c['suspended_amount'] = sum([owned_license.charge_amount or 0 for owned_license in log.owned_licenses.all()])