我添加了代码,因此用户在尝试保存故事时最多可以将两种类型的故事联系起来,这会给标题带来错误。
class Story(models.Model):
title = models.CharField(max_length=255)
genre = models.ManyToManyField(Genre)
alias = models.CharField(max_length=255, null=True, blank=True)
def save(self, *args, **kwargs):
self.alias = slugify(self.title, 'ru')
return super(Story, self).save(*args, **kwargs)
def clean(self, *args, **kwargs):
if self.genre.count() > 2:
raise ValidationError('Error')
super(Story, self).clean(*args, **kwargs)
答案 0 :(得分:1)
在设置多对多关系之前,必须先保存两个对象以获得id
值。这是因为使用包含所有(story.id,genre.id)对的第三个数据库表存储了多对多关系。您想要类似的东西:
my_genre = Genre(name='Fable')
my_genre.save()
my_story = Story(title='The Tortoise and the Hare')
my_story.save()
# now that my_genre.id and my_story.id are defined, the many-to-many relationship can be set:
my_story.genre.set([my_genre])
my_story.save()