我有一個非常簡單的方法:測試Python方法調用類的方法
Class Team(models.Model):
def sides(self):
return SideNames.objects.filter(team=self)
SideNames是在同一個文件作爲團隊定義的另一個模型,
當我嘗試這和測試:
self.assertEquals(len(t.sides()), 2)
我得到以下錯誤:
return SideNames.objects.filter(team=self)
AttributeError: 'NoneType' object has no attribute 'objects'
但如果我更改測試是
self.assertEquals(len(SideNames.objects.filter(team=t)), 2)
然後,我沒有得到錯誤。從測試本身調用SideNames.objects.filter和調用實際方法有什麼區別?
作爲參考,這裏是整個2類。
class Team(models.Model):
"""The model for a football team."""
class Admin:
pass
def __unicode__(self):
return u'%s' % self.name
def is_player(self, player):
"""Checks to see if 'player' is a member if this team. Returns True if they are, or False otherwise."""
try:
teamPlayer = TeamPlayers.objects.get(player=player, team=self)
return True
except ObjectDoesNotExist:
return False
def sides(self):
"""Return the side names for this team"""
return SideNames.objects.filter(team=self)
def updateSides(self, side_a, side_b):
"""Update the side names"""
names = SideNames.objects.filter(team=self);
a = SideNames.objects.get(name = names[0].name)
a.name = side_a
a.save()
b = SideNames.objects.get(name = names[1].name)
b.name = side_b
b.save()
name = models.CharField("Team Name", max_length=255)
organiser = models.ForeignKey(User)
class SideNames(models.Model):
"""Holds the names of the sides for each team"""
class Admin:
pass
def __unicode__(self):
"""Pretty print the SideNames object"""
return self.name
team = models.ForeignKey(Team)
name = models.CharField(max_length=128)
'sides'是一種方法,不是類方法。 – 2010-02-13 01:08:48