Django 2.0以降、ORMに組み込まれています。ウィンドウ関数を参照してください
# models.py
class GameScore(models.Model):
user_id = models.IntegerField()
score = models.IntegerField()
# window function usage
from django.db.models.expressions import Window
from django.db.models.functions import Rank
GameScore.objects.annotate(rank=Window(
expression=Rank(),
order_by=F('score').desc(),
partition_by=[F('user_id')]))
# generated sql
SELECT "myapp_gamescore"."id",
"myapp_gamescore"."user_id",
"myapp_gamescore"."score",
RANK() OVER (
PARTITION BY "myapp_gamescore"."user_id"
ORDER BY "myapp_gamescore"."score" DESC
) AS "rank"
FROM "myapp_gamescore"