How to Order By Count of a ForeignKey field in Django

1 min read

Sometimes in Django you'll want to order a QuerySet by the count of another model that has a ForeignKey relationship to the model you're querying.

As a simple example, say you have two basic models User and Post:

# app/models.py from django.db import models class User(models.Model): username = models.CharField(max_length=100) class Post(models.Model): author = models.ForeignKey(User) title = models.CharField(max_length=250) content = models.TextField()

Now you want to create a QuerySet with users ordered by the number of users with the most Posts. To do this you can use annotate and Count to create a count of posts for each user and then order by that count.

# app/views.py from django.db.models import Count from app.models import User top_authors = User.objects.all() \ .annotate(num_posts=Count('post')) \ .order_by('-num_posts')


Author picture
Rhett Trickett

Founder at Able

@rhett RhettTrickett rhetttrickett
Django

Join the discussion

Able is a developer community where people build their coding knowledge and careers.

Join with GitHub Join with Twitter