Ethan Peck
Ethan Peck

Reputation: 37

Sort Django models based on the maximum value of multiple fields

I have a model that stores data for teams. Each team has three fields for each match played (match1, match2, etc.) that store a point value. I need to be able to sort these teams based on the highest score in any of the three matches, but Django's order_by method only sorts based on the max of one value. Is there a way for me to provide multiple parameters and have it choose the greatest value when sorting? Here is what my code looks like so far:

#models.py
class Team(models.Model):
    match1 = models.CharField(max_length=4, blank=True, default="/")
    match2 = models.CharField(max_length=4, blank=True, default="/")
    match3 = models.CharField(max_length=4, blank=True, default="/")
#views.py
def team_rankings(request): # Scoreboard/rankings of teams
    context = {
        'teams': Team.Objects.all().order_by(#All three match results here)
    }
    return render(request, 'scoring_system/rankings.html', context)

Upvotes: 1

Views: 114

Answers (1)

aminrd
aminrd

Reputation: 4980

You can add a function to your class Team that returns the maximum value of those matches like :

#models.py
class Team(models.Model):
    match1 = models.CharField(max_length=4, blank=True, default="/")
    match2 = models.CharField(max_length=4, blank=True, default="/")
    match3 = models.CharField(max_length=4, blank=True, default="/")

    def highest(self):
        # Compares self.match1, self.match2, self.match3 and returns highest

Then, you can sort them using:

#views.py
def team_rankings(request): # Scoreboard/rankings of teams
    context = {
        'teams': sorted( Team.objects.all(), key=lambda x: x.highest() )
    }
    return render(request, 'scoring_system/rankings.html', context)

Upvotes: 1

Related Questions