Returning values from calculations done by custom methods in models

199 views
Skip to first unread message

Gchorn

unread,
Feb 18, 2012, 8:38:30 PM2/18/12
to Django users
Hello All,

So in my models.py file, I have:

class Player(models.Model):
team = models.ForeignKey(Team)
first_name = models.CharField(max_length=100)
last_name = models.CharField(max_length=100)
gp = models.IntegerField(max_length=2) #games played
mp = models.IntegerField(max_length=4) #minutes played
def mpg(self): #minutes per game
return self.mp/self.gp
def __unicode__(self):
return self.first_name+' '+self.last_name

When I run "python manage.py shell" and try to pull up a player's
"mpg", I get:

>>> p = Player.objects.get(last_name='Durant')
>>> p
<Player: Kevin Durant>
>>> p.mp
1027
>>> p.gp
27
>>> p.mpg
<bound method Player.mpg of <Player: Kevin Durant>>

How do I get the API to return '38' and not <bound method of blah blah
blah>? I realize this probably has something to do with telling the
models.py file how to represent p.mpg with some kind of __unicode__()
method, but I don't know exactly what that code should be or where it
should go relative to the "def mpg(self)" method...

akaariai

unread,
Feb 18, 2012, 8:47:46 PM2/18/12
to Django users
mpg is a method, so call it:
p.mpg()

If you want to have p.mpg returning the value, you could use a
property:
def _get_mpg(self):
return self.mp/self.gp
mpg = property(_get_mpg)

There isn't anything special about models.py in this regard, this is
just standard Python. So, I suggest learning a little more about
Python. If you go through trial-error learning here you are in for a
long ride.

- Anssi

Gchorn

unread,
Feb 18, 2012, 10:46:42 PM2/18/12
to Django users
Whoops, wow that really was basic Python. Sorry for the spam; of
course I know there's a difference between calling a method and
calling an attribute...how embarassing. =)

Thanks for your help Anssi. Also thanks for not adding, ", you
moron!" to the end of each sentence...
Reply all
Reply to author
Forward
0 new messages