Last active
October 28, 2020 05:55
-
-
Save mrhwick/b40ad6c6ecb6b69d521f6aded072b8c2 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from collections import defaultdict | |
points = BallotEntry.objects.values( | |
'ballot__poll_id', | |
'team', | |
).filter( | |
ballot__submission_date__isnull=False | |
).annotate( | |
points=Sum(26-F('rank')) | |
) | |
num_votes = Ballot.objects.filter( | |
submission_date__isnull=False | |
).annotate( | |
Count('poll_id'), | |
).values('poll_id').annotate( | |
num_votes=Count('id') | |
).values('poll_id', 'num_votes') | |
votes_per_poll = {nv.get('poll_id'): nv.get('num_votes') for nv in num_votes} | |
teams_by_poll = defaultdict(list) | |
for p in points: | |
p['ppv'] = p.get('points') / votes_per_poll[p.get('ballot__poll_id')] | |
points_by_poll[p.get('ballot__poll_id')].append(p) | |
[teams_by_poll[p.get('ballot__poll_id')].append(p) for p in points] | |
for poll in Poll.objects.all().order_by('year', 'week'): | |
teams = teams_by_poll[poll.id] | |
sorted_teams = sorted(teams, key=lambda x: x.get('points')) | |
for i, team in enumerate(sorted_teams): | |
team['rank'] = len(sorted_teams) - i | |
teams_by_poll[poll_id] = sorted_teams | |
if poll.last_week: | |
for i, team in enumerate(sorted_teams): | |
last_week_team = next( | |
(t for t in teams_by_poll[poll.last_week.id] if t.get('team') == team.get('team')), | |
None | |
) | |
if last_week_team: | |
if 'rank' in last_week_team: | |
team["rank_diff"] = last_week_team.get('rank') - team.get('rank') | |
team['lw_rank'] = last_week_team.get('rank') | |
if 'ppv' in last_week_team: | |
team['lw_ppv'] = last_week_team.get('ppv') | |
team["ppv_diff"] = team.get('ppv') - last_week_team.get('ppv') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment