Fred Collins
Fred Collins

Reputation: 5010

Django queryset ordering by _set

I've this models:

class Person(models.Model):
    name = models.CharField()
    likes = models.ManyToManyField(Image)

class Image(models.Model):
    name = ...
    image = ...

If I use [x.person_set.count() for x in Image.objects.all()] I get how many people likes every image.

Now I need to order the list. I want something like Image.objects.all().order_by('person_set.count()')

I need to get a list of all images ordered by how much people likes it.

How can I do it?

Upvotes: 2

Views: 586

Answers (1)

Issac Kelly
Issac Kelly

Reputation: 6359

This does everything you want (# of likes, and order by count) in one query.

from django.db.models import Count
Image.objects.annotate(Count("person")).order_by("person__count")

Upvotes: 1

Related Questions