Django ManyToMany模型验证 [英] Django ManyToMany model validation

查看:110
本文介绍了Django ManyToMany模型验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个与这个类似的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管理员)时,我得到'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

    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中使用您的表单admin。

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 ManyToMany模型验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆