Django 多对多模型验证 [英] Django ManyToMany model validation
问题描述
我有一个类似这个模型的 ManyToManyField 模型(模型 Word 也有一种语言):
I have a model with a ManyToManyField similar to this one (the model Word has a language, too):
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')
当尝试添加一个新句子时(例如通过 django admin),我得到 'Sentence' 实例需要有一个主键值才能使用多对多关系
.这意味着我无法在保存之前访问 self.words,但这正是我想要做的.有什么办法可以解决这个问题,这样你就可以验证这个模型吗?我真的很想直接验证模型的字段.
When trying to add a new sentence (e.g. through django admin) I get 'Sentence' instance needs to have a primary key value before a many-to-many relationship can be used
. This means I can't access self.words before saving it, but this is exactly what I'm trying to do. Is there any way to work around this so you can validate this model nevertheless? I really want to directly validate the model's fields.
我发现了很多关于这个异常的问题,但我找不到解决我的问题的帮助.我将不胜感激任何建议!
I found many questions concerning this exception, but I couldn't find help for my problem. I would appreciate any suggestions!
推荐答案
无法在模型的 clean
方法中进行此验证,但您可以创建一个模型表单来验证选择词
.
It is not possible to do this validation in the model's clean
method, but you can create a model form which can validate the choice of words
.
from django import forms
class SentenceForm(forms.ModelForm):
class Meta:
model = Sentence
fields = ['words', 'language']
def clean(self):
"""
Checks that all the words belong to the sentence's language.
"""
words = self.cleaned_data.get('words')
language = self.cleaned_data.get('language')
if language and words:
# only check the words if the language is valid
for word in words:
if words.language != language:
raise ValidationError("The word %s has a different language" % word)
return self.cleaned_data
然后您可以自定义您的 Sentence
模型管理类,以在 Django 管理中使用您的表单.
You can then customise your Sentence
model admin class, to use your form in the Django admin.
class SentenceAdmin(admin.ModelAdmin):
form = SentenceForm
admin.register(Sentence, SentenceAdmin)
这篇关于Django 多对多模型验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!