[Django]-Keeping annotated rank when filtering Django

2👍

You can use django-cte library

from django_cte import CTEManager, With

# models.py
class Choice(Model):
    objects = CTEManager()
    # ... other fields like tournament

# query 
cte = With(
Choice.objects.filter(tournament=pk).annotate \
(rank=RawSQL("RANK() OVER(ORDER BY winrate DESC, pickrate DESC,times_played)", [])))
qs = cte.queryset().with_cte(cte).filter(title__icontains='an')

and follow this link.

Leave a comment