[Fixed]-Annotating SUM aggregation function leading to 'None' value in Django


Just hit the same wall, although I chose to ignore None entries by excluding them out of the results. Guess you don’t want that.

BTW, this question has the same issue Annotating a Sum results in None rather than zero

As for the solution other than using a custom sql as pointed out in that question’s answer, you can use Django 1.8 instead and go for the solution pointed out in the ticket open in Django’s bug tracker for over 6 years(!) https://code.djangoproject.com/ticket/10929

Coalesce(Sum('field'), 0)

So your manager would be:

class LinkVoteCountManager(models.Manager):
    def get_query_set(self):
        return super(LinkVoteCountManager, self).get_query_set().annotate(
            votes=Coalesce(Sum('vote__value'), 0)

PS: I have not tested the code, since I’m not using Django 1.8 myself.


You could also replace the line

netvotes = self.votes


netvotes = self.votes or 0

and you can now remove the if statement.

What this does as in many other languages is to return the non falsy value (None, 0, “”), or the last value, ‘0’ in this particular case.

Leave a comment