Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 1011243
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 16, 20262026-05-16T09:12:19+00:00 2026-05-16T09:12:19+00:00

I have 3 django models (simplified for this example): class Fighter (models.Model): name =

  • 0

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!

  • 1 1 Answer
  • 1 View
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-16T09:12:19+00:00Added an answer on May 16, 2026 at 9:12 am

    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)
        .
        .
        .
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have the following abstract Django models: class Food(models.Model): name = models.CharField(max_length=100) class Meta:
Consider this model (simplified for this question): class SecretAgentName(models.Model): name = models.CharField(max_length=100) aliases =
I have a basic Django model like: class Business(models.Model): name = models.CharField(max_length=200, unique=True) email
I have the following (simplified) models: class School(models.Model): name = models.CharField(max_length=128) class UserProfile(models.Model): school
I have Django models as follows: class Subject(models.Model): name = models.CharField(max_length=35, unique=True) class Book(models.Model):
in a django-tastypie app I have the following Django-models: class Car(models.Model): name=models.CharField('name',max_length=64) class CarTrack(models.Model):
I have this model in django: class JournalsGeneral(models.Model): jid = models.AutoField(primary_key=True) code = models.CharField(Code,
Consider I have defined the following models: class Tag(models.Model): name = models.CharField(max_length=20) class Entry(models.Model):
I have django objects: class Event(models.Model): title = models.CharField(max_length=255) event_start_date = models.DateField(null=True, blank='true') ...
I have 2 Django models : class A(models.Model): uniq_name = models.CharField(max_length=30,primary_key=True) info1 = models.CharField(max_length=30)

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.