开发者

django sort by manytomany relationship

开发者 https://www.devze.com 2022-12-26 16:33 出处:网络
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:

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()
se开发者_运维问答rvices_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')
0

精彩评论

暂无评论...
验证码 换一张
取 消