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.
Source:stackexchange.com