要使剧集编号在季节中唯一,您可以使用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.
请注意,如果剧集编号不正确,这只会跳出保存方法。相反,您可能会引发异常。