Search code examples
djangodjango-modelswindow-functionsdense-rank

Assign a rank to a movie based on number of comments - Django


I have movies, each movie has comments added to it. I want to create a function that will rank my Movies based on a number of comments using dense ranking. This is what I got so far - the problem is, every movie always has rank 1.

commented_movies = Movie.objects.annotate(comment_count=Count('comments', distinct=True)).annotate(
            rank=Window(expression=DenseRank()
                        , order_by=F('comment_count').desc()
                        , partition_by=[F('id')]))

I guess the problem might be in partition_by, but I have no idea how to solve it. id is a primary key of the Movie.


Solution

  • Okay, that was quick. I've just figured out partition_by is not necessary - removed it and it works:

    commented_movies = Movie.objects.annotate(comment_count=Count('comments', distinct=True)).annotate(
                rank=Window(expression=DenseRank()
                            , order_by=F('comment_count').desc()
                            , partition_by=[F('id')]))