How to add additional column to Django QuerySet

前端 未结 2 1433
死守一世寂寞
死守一世寂寞 2021-02-07 08:39

I have a QuerySet with Books and I would like to add a score field to every Book result.

qs = Book.objects.all()

In raw SQL I woul

2条回答
  •  情书的邮戳
    2021-02-07 08:57

    If votes possible values are only 1 and -1 you can just sum them using mentioned annotate: Book.objects.annotate(score=Sum('votes__value')).

    If there is more possible values you can filter annotation by adding .filter(votes__value__range=(1,1)) to the above query.

    If it's more complex you would have to use extra with select.

提交回复
热议问题