Python Convert None to a Decimal -


how convert none object decimal object in python.

code:

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

error:

typeerror: unsupported operand type(s) +: 'decimal.decimal' , 'nonetype' 

just skip values:

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

i removed [..] square brackets; sum() takes iterable, supplied using generator expression. square brackets list comprehension instead, needlessly build full list of values first. sum needs values 1 one, don't need exist @ once front.

better yet, ask database include rows charge_amount not null:

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

best still, ask database summing 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 aggregation documentation.


Comments

Popular posts from this blog

javascript - gulp-nodemon - nodejs restart after file change - Error: listen EADDRINUSE events.js:85 -

Fatal Python error: Py_Initialize: unable to load the file system codec. ImportError: No module named 'encodings' -

javascript - oscilloscope of speaker input stops rendering after a few seconds -