5. How to order on an annotated field?ΒΆ

You have two models, Category and Hero.

class Category(models.Model):
    name = models.CharField(max_length=100)


class Hero(models.Model):
    # ...
    name = models.CharField(max_length=100)
    category = models.ForeignKey(Category, on_delete=models.CASCADE)

You want to get the Category, ordered by number of Hero in them. You can do this.

Category.objects.annotate(
    hero_count=Count("hero")
).order_by(
    "-hero_count"
)