Annotating a Sum results in None rather than zero

后端 未结 2 454
刺人心
刺人心 2021-01-31 14:03

I\'m making a QA site that is similar to the page you\'re on right now. I\'m attempting to order answers by their score, but answers which have no votes are having their score

2条回答
  •  后悔当初
    2021-01-31 14:21

    What about you use custom Manager? For example:

    AnswerManager(models.Manager):
        def all_with_score(self):
           qs = self.get_query_set().annotate(score=Sum('vote__type'))
           # Here, you can do stuff with QuerySet, for example
           # iterate over all Answers and set 'score' to zero if None.
    
    Answer(models.Model):
        //some fields here
        objects = AnswerManager()
    

    Then, you can use:

    >>> answers = Answer.objects.all_with_score().order_by('-score')
    

提交回复
热议问题