如何基于Django中的两个字段对queryset进行排序?

时间:2019-05-30 19:04:42

标签: python django python-3.x django-rest-framework django-views

这是我的serilizer类:

class RankNewsChannelSerializers(serializers.ModelSerializer):
    class Meta:
        model = News_Channel
        fields = ('id', 'name','total_star', 'total_user')

这是我的观点:

class NewsChannelRankApi(ListAPIView):
    queryset = News_Channel.objects.order_by('-total_star').all()
    serializer_class = RankNewsChannelSerializers

我得到的响应是根据total_stars进行排序的,如下所示:

[
    {
        "id": 9,
        "name": "The Hindu",
        "total_star": 36,
        "total_user": 5
    },
    {
        "id": 1,
        "name": "NDTV",
        "total_star": 36,
        "total_user": 5
    },
    {
        "id": 10,
        "name": "Firstpost",
        "total_star": 35,
        "total_user": 6
    },
    {
        "id": 14,
        "name": "DD News",
        "total_star": 25,
        "total_user": 4
    }
]

但是我需要将响应按total_star/total_user进行排序。 像这样是我无效的方法,但是它将使您大致了解我想要实现的目标。

class NewsChannelRankApi(ListAPIView):
    queryset = News_Channel.objects.order_by('-total_star/total_user').all()
    serializer_class = RankNewsChannelSerializers

如果有帮助,请帮助我吗?

1 个答案:

答案 0 :(得分:2)

您可以添加具有所需值的字段,然后按其排序。 另外,您不需要.all()

    queryset = News_Channel.objects \
         .annotate(stars_per_user=F('total_star')/F('total_user')) \
         .order_by('-stars_per_user')