我有一个与此类似的ManyToManyField模型(模型Word也有一种语言):
class Sentence(models.Model):
words = models.ManyToManyField(Word)
language = models.ForeignKey(Language)
def clean(self):
for word in self.words.all():
if word.language_id != self.language_id:
raise ValidationError('One of the words has a false language')
Run Code Online (Sandbox Code Playgroud)
在尝试添加新句子时(例如通过django admin),我得到了'Sentence' instance needs to have a primary key value before a many-to-many relationship can be used.这意味着在保存之前我无法访问self.words,但这正是我想要做的.有没有办法解决这个问题,所以你可以验证这个模型吗?我真的想直接验证模型的字段.
我发现了很多关于这个例外的问题,但我无法找到解决问题的方法.我很感激任何建议!