开发者

Ascending/descending ordering of Django QuerySet when one attribute is a model method

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 win开发者_C百科ning 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)


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)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜