django sort by manytomany relationship

Posted by Marconi on Stack Overflow See other posts from Stack Overflow or by Marconi
Published on 2010-04-11T13:06:55Z Indexed on 2010/04/11 13:13 UTC
Read the original article Hit count: 245

Filed under:

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?

© Stack Overflow or respective owner

Related posts about django