[Django]-Django ORM: create ranking based on related model count

4👍

RowNumber should be sufficient if the query is appropriately ordered:

from django.db.models import Count
from django.db.models.expressions import F, Window
from django.db.models.functions.window import RowNumber

qs = (Movie.objects
    .annotate(total_comments=Count('comment'))
    .order_by('total_comments')
    .annotate(rank = Window(expression=RowNumber())
)

But since the row number is inherent in the sequence of the records, Kevin is right in suggesting an easy Python method (e.g. enumerate) as you’re going to be iterating over the recordset at some point anyway.

It would be different if you wanted a different ordering for your recordset than for the ranking, then it would make sense to use Window with a separate order_by parameter.

I’m not sure if RowNumber is supported by all backends.

Leave a comment