Home > database >  How to show if there are duplicates in enumerate
How to show if there are duplicates in enumerate

Time:10-14

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

CodePudding user response:

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)

CodePudding user response:

I don't see any way to adjust enumerate in this case unfortunately. You'll have to store your own counter and compare to last each iteration:

rank = 0
last_points = -1
for value in NFLTeamStats.objects.all().values('name', 'avg_points').order_by('-avg_points')
        if value['name'] == team.pk:
            if value['avg_points'] > last_points:
                rank  = 1
            avg_points_rank = rank
            last_points = value['avg_points']
  • Related