我想为一个模型创建一个自然键,它是两个值的组合。
我尝试了以下方法:
class TeamManager(models.Manager):
def get_by_natural_key(self, name):
return self.get(name=name)
class Team(models.Model):
objects = TeamManager()
name = models.CharField(max_length=100, unique=True)
def natural_key(self):
return name
class SeasonManager(models.Manager):
def get_by_natural_key(self, team, year):
return self.get(team=team.natural_key(), year=year)
class Season(models.Model):
objects = SeasonManager()
year = models.CharField(max_length=25, choices=YEARS)
team = models.ForeignKey(Team)
def natural_key(self):
return "%s-%s"%(self.team.natural_key(),self.year)
natural_key.dependencies = ['league.Team']
当我尝试通过其自然键“Atlanta Falcons”、“2013-1014”访问季节模型时,我得到了这个异常:
ValueError: invalid literal for int() with base 10: 'Atlanta Falcons'