darkhorse
darkhorse

Reputation: 8782

How to order a queryset by related objects count?

My models.py is currently set up as follows:

class Topic(models.Model):
    topic = models.CharField(max_length = 50)

    def __str__(self):
        return self.topic

class Comic(models.Model):
    ...
    topic = models.ForeignKey(Topic, blank = True, null = True,
    related_name = 'comics')

Anyway, from this its understandable that 2 comics can share the same topic, however, each comic can only have one topic. Now I need a list of objects of the Topic model ordered according to the number of Comic objects associated with them. For example, say I have a Topic called Unsorted which is associated with 15 comics and another Topic called Funny with 5 comics. I want my query set to be ordered in a way that the Unsorted comes before the Funny object.

Topic.objects.all().order_by('-comics')

I tried this but it did not really work, the result wasn't sorted the right way, even though there wasn't an error. So any solutions? Thanks!

Upvotes: 1

Views: 589

Answers (1)

Ivan
Ivan

Reputation: 6013

You can do this:

from django.db.models import Count

# ...    

Topic.objects.annotate(cc=Count('comic')).order_by('-cc')

Upvotes: 4

Related Questions