我是Django的新手,我不确定如何处理以下问题:
我有模特:
class Season(models.Model):
number_of_episodes = models.IntegerField()
class Episode(models.Model):
season = models.ForeignKey(Season)
number = models.IntegerField()
剧集编号不仅应该在季节中独一无二,还要小于季节的number_of_episodes。
答案 0 :(得分: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.
请注意,如果剧集编号不正确,这只会跳出保存方法。你可能会提出异常。