无法在模型的clean方法中进行此验证,但是你可以创建一个模型表单来验证的选择words
。
from django import forms
class SentenceForm(forms.ModelForm):
class Meta:
model = Sentence
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管理员中使用表单。
class SentenceAdmin(admin.ModelAdmin):
form = SentenceForm
admin.register(Sentence, SentenceAdmin)