How to Order By Count of a ForeignKey field in Django

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')


Thank you so much! ^^

Michael Skyba picture

Thank you!