[英]How to sort queryset based on two fields in Django?
This is my serilizer class: 这是我的serilizer课:
class RankNewsChannelSerializers(serializers.ModelSerializer):
class Meta:
model = News_Channel
fields = ('id', 'name','total_star', 'total_user')
This is my view: 这是我的看法:
class NewsChannelRankApi(ListAPIView):
queryset = News_Channel.objects.order_by('-total_star').all()
serializer_class = RankNewsChannelSerializers
The response I'm getting is sorted, based on total_stars
, as shown below: 我得到的响应是基于
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
}
]
But I need the response to be sorted by total_star/total_user
. 但我需要将响应按
total_star/total_user
排序。 Like this is my invalid method, but it will give you a rough idea of what I want to achieve. 像这样,这是我无效的方法,但是它将使您大致了解我想要实现的目标。
class NewsChannelRankApi(ListAPIView):
queryset = News_Channel.objects.order_by('-total_star/total_user').all()
serializer_class = RankNewsChannelSerializers
Please help me if there is anyway to do so? 如有需要,请帮助我吗?
You can add a field with the value you want and then order by it. 您可以添加具有所需值的字段,然后对其进行排序。 Also, you don't need the
.all()
另外,您不需要
.all()
queryset = News_Channel.objects \
.annotate(stars_per_user=F('total_star')/F('total_user')) \
.order_by('-stars_per_user')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.