views:

18

answers:

1

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:

  1. The "sort" is neither correct nor consistent.
  2. 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!

A: 

I've managed to solve both problems:

  1. I was appending the collection of wins, not the "length" of that list. I needed to change this:

    wins.append((fighter.id, get_fighter_wins(fighter)),)

    to:

    wins.append((fighter.id, len(get_fighter_wins(fighter))),)

  2. I was constructing a list of querysets, not a list of objects. I needed to change this:

    winners.append(Fighter.objects.filter(id=win[0]))

    to:

    winners.append(Fighter.objects.get(id=win[0]))

(Cheers to my friend Attila who explained the second issue to me.)

BTW, my final code doesn't use three separate functions. Instead I did this:

    .
    .
    .

class WeightGroup:
    .
    .
    .
            def sort (self, sort_function):
                scores = []
                scorers = []

                for fighter in self.fighters:
                    scores.append((fighter.id, len(sort_function(fighter))),)
                for score in (sorted(scores, key=lambda f: f[1], reverse=True)):
                    scorers.append(Fighter.objects.get(id=score[0])) 

                self.fighters = scorers
    .
    .
    .
        if sort in ['wins', 'losses', 'draws']:
            title += ', sorted by ' + sort
            for weight_group in weight_groups:
                if (sort == 'wins'): weight_group.sort(get_fighter_wins)
                if (sort == 'losses'): weight_group.sort(get_fighter_losses)
                if (sort == 'draws'): weight_group.sort(get_fighter_draws)
    .
    .
    .
Brian Kessler