views:

34

answers:

1

I have a QuerySet of teams ordered by school name. One of the attributes is a model method that keeps track of the team's winning percentage. I want to order the teams from highest winning percentage to lowest. If teams have the same winning percentage, I want them to be ordered alphabetically by school. How do I get something like this:

team  pct
x    0.75
a    0.50
b    0.50
c    0.50
y    0.25

Because the winning percentage is a model method, I've been using Python to sort a QuerySet that is already in alphabetical order, but the alphabetical order of the schools is lost when I do this:

team_list = Team.objects.order_by('school')
sorted_team_list = sorted(team_list, key=lambda x: x.win_pct, reverse=True)
+1  A: 

Do it in two steps, not bad since sorts are stable:

from operator import attrgetter

sorted_team_list = sorted(team_list, key=attrgetter('school'))
sorted_team_list = sorted(sorted_team_list, key=attrgetter('win_pct'), reverse=True)
ars
Thanks for response, but the schools would be in reverse alphabetical order. How do I reverse the win_pct and not the school?
dhh9
Ah, see update.
ars