无法在模型的clean方法中进行此验证,但是你可以创建一个模型表单来验证的选择
words。
from django import formsclass 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 = SentenceFormadmin.register(Sentence, SentenceAdmin)



