Django嵌套for循环中forloop.counter不重置的排名计数问题
Hey, let's break down why your rank counter is acting up and how to fix it quickly.
The Root Cause
Right now, your template loops through all stats entries first, then uses an if check to filter for the current division. The forloop.counter variable counts every iteration of the full stats loop—even the ones you skip with the if condition. That's why you're seeing weird numbers like 1,3,4 for Division A and 2,5,6 for Division B: the counter never resets when switching divisions.
The Simple Fix (Using Your Existing View Data)
Good news—your view already does the hard work of grouping stats by division with the divisions_and_stats variable! You just need to use that directly in your template instead of looping through divisions and stats separately.
Here's the updated template code:
{% for division, division_stats in divisions_and_stats %} <h4>{{ division }}</h4> <table class="table"> <tr> <td align="center">Place</td> <td>Team</td> <td align="center">Points</td> </tr> {% for stat in division_stats %} <tr> <td width="10%" align="center">{{ forloop.counter}}</td> <td width="70%">{{ stat.team }}</td> <td width="20%" align="center">{{ stat.points }}</td> </tr> {% endfor %} </table> {% endfor %}
Why This Works
divisions_and_statsis a list of tuples where each tuple is(division_name, list_of_team_stats_for_that_division)- The inner loop only iterates over the stats specific to the current division, so
forloop.counterresets to 1 every time you start a new division's table. No more skipped counts messing things up!
Bonus: Optimize Your View (Optional)
If you want to make your view more efficient (especially as your team count grows), you can replace the list comprehension with itertools.groupby—since your stats queryset is already sorted by division, grouping is a one-pass operation:
from itertools import groupby def seasonstandings(request): stats = WeeklyStats.objects.values('player__team__team_name').annotate( team=F('player__team__team_name'), points=Sum('finishes'), division=F('player__team__division__name') ).order_by('division', '-points') # Group stats by division in one pass divisions_and_stats = [] for division, group in groupby(stats, key=lambda x: x['division']): divisions_and_stats.append( (division, list(group)) ) return render(request, 'website/seasonstandings.html', { 'divisions_and_stats': divisions_and_stats })
This avoids looping through the entire stats list once per division (which your original list comprehension does), making it faster for larger datasets.
内容的提问来源于stack exchange,提问作者jAC

