Annotating a Sum results in None rather than zero

后端 未结 2 456
刺人心
刺人心 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:17

    You can use the Coalesce function from django.db.models.functions like:

    answers = (Answer.objects
        .filter()
        .annotate(score=Coalesce(Sum('vote__type'), 0))
        .order_by('-score'))
    

提交回复
热议问题