Order by Model Method?

16 views
Skip to first unread message

HBTaylor

unread,
Jun 5, 2006, 3:51:57 PM6/5/06
to Django users
I am learning Django by working on a baseball stats tracking
application. In it, I have a Team model, like this:

class Team(models.Model):
name = models.CharField(maxlength=200)

Teams participate in games (in a Game model), either as the home team
or the visiting team. I have a method in the Team model which
calculates the team's record (wins/losses/ties). I want to have show
(and sort by) the team's "winning percentage" (one point per win, 0.5
points per tie, 0 points for a loss - divided by the number of games
played). I have a win_percentage() method defined for the model, but
I'm at a loss for how to sort by it for views/templates.

Since the method doesn't correspond to a column in a table, the
order_by() method doesn't work. I want to show all teams by descending
winning percentage in a "standings" view, but I'm not sure what way to
best accomplish this. I have ideas in my head about iterating over the
Team.objects.all() and creating some kind of dict with that information
in it, but that seems a little counter-intuitive.

Has anyone solved this in the past, or is there someplace in the
documentation which might help?

H.B.

Luke Plant

unread,
Jun 10, 2006, 10:37:48 AM6/10/06
to django...@googlegroups.com
On Monday 05 June 2006 20:51, HBTaylor wrote:

> Since the method doesn't correspond to a column in a table, the
> order_by() method doesn't work. I want to show all teams by
> descending winning percentage in a "standings" view, but I'm not sure
> what way to best accomplish this. I have ideas in my head about
> iterating over the Team.objects.all() and creating some kind of dict
> with that information in it, but that seems a little
> counter-intuitive.
>
> Has anyone solved this in the past

http://groups.google.com/group/django-users/search?group=django-users&q=ordering+model+methods&qt_g=1&searchnow=Search+this+group

Luke

--
The probability of someone watching you is proportional to the
stupidity of your action.

Luke Plant || L.Plant.98 (at) cantab.net || http://lukeplant.me.uk/

Reply all
Reply to author
Forward
0 new messages