[Answered ]-How do I order by highest number of likes on blog posts?

1👍

You can make a manager that will annotate and order by:

from django.db.models import Count


class PostManager(models.Manager):
    def get_queryset(self, *args, **kwargs):
        return (
            super()
            .get_queryset(*args, **kwargs)
            .alias(nlikes=Count('likes'))
            .order_by('-nlikes')
        )


class Post(models.Model):
    # …
    objects = PostManager()

You can then still use Post._base_manager.all() to avoid ordering.

Leave a comment