2

我是 Django 新手,不知道如何处理以下问题:

我有模型:

class Season(models.Model):
    number_of_episodes = models.IntegerField()
class Episode(models.Model):
    season = models.ForeignKey(Season)
    number = models.IntegerField()

剧集编号不仅应在季节中唯一,而且应小于季节的 number_of_episodes。

4

1 回答 1

2

要使剧集编号在季节中唯一,您可以使用unique_together。这意味着对于一个字段的每个值,在另一个字段中只能有一行具有值。那看起来是这样的:

class Season(models.Model):
    number_of_episodes = models.IntegerField()
class Episode(models.Model):
    class Meta:
        unique_together = (season, number)
    season = models.ForeignKey(Season)
    number = models.IntegerField()

我不认为你可以使用 django 模型来强制剧集编号应该小于 season.number_of_episodes,但你可以在覆盖的保存方法中做到这一点。像这样的东西:

class Season(models.Model):
    number_of_episodes = models.IntegerField()

class Episode(models.Model):
    class Meta:
        unique_together = (season, number)
    season = models.ForeignKey(Season)
    number = models.IntegerField()

    def save(self, *args, **kwargs):
        if self.number > season.number_of_episodes:
            return #Don't save
        else:
            super(Episode, self).save(*args, **kwargs) # Call the "real" save() method.

请注意,如果剧集编号不正确,这只会跳出保存方法。相反,您可能会引发异常。

于 2012-05-12T21:39:12.757 回答