简体   繁体   中英

Python Convert None to a Decimal

How would I convert a None object to a Decimal object in Python.

Code:

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

Error:

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

Just skip those values:

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

I removed the [..] square brackets; sum() takes an iterable, which I supplied by using a generator expression . With the square brackets it is a list comprehension instead, which will needlessly build a full list of all values first. Sum just needs the values one by one, they don't need to exist all at once up front.

Better yet, ask the database to only include those rows where charge_amount is not NULL :

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

Best still, ask the database to do the summing for you:

from django.db.models import Sum

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

See the Aggregation documentation .

您也可以使用'或'运算符:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM