Django自然键,两个值的组合?

时间:2013-09-21 03:22:57

标签: python django django-models key

我想为一个两个值组合的模型创建一个自然键。

我尝试过以下方法:

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']

当我尝试通过其自然键“亚特兰大猎鹰队”,“2013-1014”访问赛季模型时,我得到了这个例外:

ValueError: invalid literal for int() with base 10: 'Atlanta Falcons'

2 个答案:

答案 0 :(得分:1)

而不是返回2个值的字符串作为

的自然键返回元组
def natural_key(self):
    return (self.team.natural_key(),self.year)

答案 1 :(得分:0)

以下修复程序适用于我:

class SeasonManager(models.Manager):
    def get_by_natural_key(self, team, year):
        return self.get(team=Team.objects.get_by_natural_key(team), year=year)