Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Convert None to a Decimal

Tags:

python

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'
like image 836
Dusty Avatar asked Apr 30 '26 21:04

Dusty


2 Answers

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.

like image 55
Martijn Pieters Avatar answered May 03 '26 12:05

Martijn Pieters


You can also use the 'or' operator:

c['suspended_amount'] = sum([owned_license.charge_amount or 0 for owned_license in log.owned_licenses.all()])
like image 25
Ali SAID OMAR Avatar answered May 03 '26 12:05

Ali SAID OMAR



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!