简体   繁体   English

Django 按多对多关系排序

[英]django sort by manytomany relationship

I have the following model:我有以下模型:

class Service(models.Model):
    ratings = models.ManyToManyField(User)

Now if I wanna get all the service with ratings sorted in descending order I did something:现在,如果我想获得按降序排序的所有服务,我做了一些事情:

services_list = Service.objects.filter(ratings__gt=0).distinct()
services_list = list(services_list)
services_list.sort(key=lambda service: service.ratings.all().count(), reverse=True)

As you can see its a three step process and I don't feel right about this.正如你所看到的,它是一个三步过程,我对此感觉不对。 Anybody who knows a better way to do this?有谁知道更好的方法来做到这一点?

How about:怎么样:

from django.db.models import Count
service_list = Service.objects.annotate(ratings_num=Count('ratings')).filter(ratings_num__gt=0).order_by('-ratings_num')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM