I have 3 django models (simplified for this example):
class Fighter (models.Model):
name = models.CharField(max_length=100)
weight_class = models.ForeignKey(WeightClass, related_name="fighter_weight_class")
class Bout (models.Model):
fighter_1 = models.ForeignKey(Fighter, related_name="bout_fighter_1")
fighter_2 = models.ForeignKey(Fighter, related_name="bout_fighter_2")
winner = models.ForeignKey(Fighter, related_name="bout_winner", blank=True,
null=True, help_text='Leave blank for draw.')
date = models.DateField()
cancelled = models.BooleanField()
class WeightClass (models.Model):
name = models.CharField(max_length=100)
I would like to be able to list the Fighters by their stats. I created these functions (which work) to calculate their wins, losses, and draws:
def get_bouts_with_fighter (fighter):
return Bout.objects.filter(fighter_1 = fighter) | \
Bout.objects.filter(fighter_2 = fighter)
def get_fighter_wins (fighter):
return Bout.objects.filter(winner=fighter)
def get_bouts_fought_not_won (fighter):
return get_bouts_with_fighter(fighter) \
.exclude(cancelled=True) \
.exclude(date__gt = datetime.datetime.now())
def get_fighter_losses (fighter):
return get_bouts_fought_not_won(fighter)\
.exclude(winner=fighter)\
.exclude(winner=None)
def get_fighter_draws (fighter):
return get_bouts_fought_not_won(fighter)\
.filter(winner=None)
But now, when comes to sorting the output for the view, I'm having two problems:
- The "sort" is neither correct nor consistent.
- During the sort, I'm losing the fighter's name
Here is the current code (the output is correct if no sorting is performed):
def list(request, sort=None):
class WeightGroup:
"""
Internal class to keep data organized by weight class.
"""
weight_class = None
fighters = None
def win_sort (self):
wins = []
winners = []
for fighter in self.fighters:
wins.append((fighter.id, get_fighter_wins(fighter)),)
for win in (sorted(wins, key=lambda f: f[1], reverse=True)):
winners.append(Fighter.objects.filter(id=win[0])) #build winner list by score
self.fighters = winners
def loss_sort (self):
#TO DO:
pass
def draw_sort (self):
#TO DO:
pass
title = 'Fighters'
weight_groups = []
for weight_class in WeightClass.objects.all():
weight_group = WeightGroup()
weight_group.weight_class = weight_class
weight_group.fighters = Fighter.objects.filter(weight_class=weight_class)
weight_groups.append(weight_group)
if sort in ['wins', 'losses', 'draws']:
title += ', sorted by ' + sort
for weight_group in weight_groups:
if (sort == 'wins'): weight_group.win_sort()
if (sort == 'losses'): weight_group.loss_sort()
if (sort == 'draws'): weight_group.draw_sort()
return render_to_response ('fighters/list.html',{
'title': title,
'weight_groups':weight_groups
})
Any suggestions how I can get this to work will be appreciated!