Search code examples
pythondjangoenumerate

How to show if there are duplicates in enumerate


I have a list of stats that I keep for every team in the NFL. Every week I have a function that goes through the whole league and using enumerate, ranks teams in each stat category and then saves to a db.

My question is... if multiple teams have the same value how do I give them the same rank?

For example if the Patriots and Giants each average 30points a game and thats the best in the league, how do I make them both rank 1 and the next team start at 3?

Below I have how I currently rank the teams now I appreciate any help or tips you can offer.

    for team in TeamName.objects.filter(league__name='NFL'):

        for count, value in enumerate(NFLTeamStats.objects.all().values(
                                          'name', 'avg_points').order_by(
                                              '-avg_points'), start=1):
                if value['name'] == team.pk:
                    avg_points_rank = count

Solution

  • You can use a Window function and Rank to annotate each row with a rank that increments in the exact way you describe

    from django.db.models import F, Window
    from django.db.models.functions import Rank
    
    for stats in NFLTeamStats.objects.annotate(
        rank=Window(expression=Rank(), order_by=F('avg_points').desc())
    ):
        print(stats, stats.rank)