1

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

我尝试了以下方法:

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

2 回答 2

1

而不是返回你2个值的字符串作为自然键返回那些作为的元组

def natural_key(self):
    return (self.team.natural_key(),self.year)
于 2013-09-21T05:28:18.997 回答
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)
于 2014-04-17T20:32:42.657 回答