Another option (better?) Is to do this in the database. You can modify your db request to match NULL with 0 using COALESCE.
Say you have a table with integer columns named col1, col2, col3 that can accept NULL.
Option 1:
SELECT coalesce(col1, 0) as col1, coalesce(col2, 0) as col2, coalesce(col3, 0) as col3 FROM your_table;
Then use sum () in Python in the returned string, without worrying about the presence of None.
Option 2: Sum the columns in the database and return the total to the query:
SELECT coalesce(col1, 0) + coalesce(col2, 0) + coalesce(col3, 0) as total FROM your_table;
Nothing more to do in Python. One of the advantages of the second option is that you can select other columns in the query that are not part of your sum (you probably have other columns in your table and you make several queries to get different columns of the table?)
source share