我应该在哪里做对象和字段的django验证? [英] Where should i do the django validations for objects and fields?

查看:135
本文介绍了我应该在哪里做对象和字段的django验证?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建一个django应用程序,它使用Django Rest Framework和plain django-views作为用户的入口点。

I'm creating a django application which uses both the Django Rest Framework and the plain django-views as entrypoint for users.

我想要做独立的验证我的模型的领域和整体上的对象。例如:

I want to do validation both independant fields of my models, and on objects on a whole. For example:


  • 字段:输入的许可证是基于正则表达式函数的正确的。与其他字段无关。

  • Field: is the entered licence-plate a correct one based on a regex function. No relation to other fields.

对象:输入的邮政编码对于给定国家/地区是否有效。关于模型中的邮政编码和国家/地区。

Object: Is the entered zipcode valid for the given country. Relates to zipcode and country in the model.

对于DRF-API,我使用ModelSerializers,它自动调用所有验证器我已经放在我的模型中,例如:

For the DRF-API i use ModelSerializers which automatically call all the validators i have placed in my Model, for example:

class MyModel(models.Model):
    licence_plate = CharField(max_length=20, validators=[LicencePlateValidator])

由于验证器在模型中给出,API POSTS(因为我使用ModelSerializer)以及django管理员后端中创建的对象都被验证。

Since the validator is given in the model, the API POSTS (because i use a ModelSerializer), as well as the objects created in the django admin backend are validated.

但是,当我想介绍对象级验证时,我需要在序列化器的 validate() -method中进行,这意味着对象只能在API中验证。

But when i want to introduce object level validation i need to do that in the serializer's validate()-method, which means objects are only validated in the API.

我也必须覆盖模型的保存方法,以验证Django管理页面中创建的对象。

I'll have to override the model's save method too, to validate the objects created in the Django admin page.

问题:这对我来说似乎有点混乱,有一个点我可以放置对象级验证器,以便它们是在API和管理页面中运行,就像我在现场级验证一样(我只需要在我的模型声明中放置它们,所有内容都被处理)

Question: This seems a bit messy to me, is there a single point where i can put the object-level validators so that they are run at the API and in the admin-page, like i did with the field-level validation (I only have to put them in my model-declaration and everything is handled)

推荐答案

对于模型级验证,有 Model.clean 方法。

For model-level validation, there is the Model.clean method.

如果您使用 ModelForm (默认在管理员中使用) ),所以这解决了django视图和管理员部分。

It is called if you are using ModelForm (which is used by default in admin), so this solves django views and admin parts.

另一方面,DRF不调用模型'自动清理,所以你必须自己在 Serializer.validate (作为 doc 建议)。你可以通过一个serializer mixin来实现:

On the other hand, DRF does not call models' clean automatically, so you will have to do it yourself in Serializer.validate (as the doc suggests). You can do it via a serializer mixin:

class ValidateModelMixin(object)
    def validate(self, attrs):
        attrs = super().validate(attrs)
        obj = self.Meta.model(**attrs)
        obj.clean()
        return attrs

class SomeModelSerializer(ValidateModelMixin, serializers.ModelSerializer):
    #...
    class Meta:
        model = SomeModel

或写一个验证器:

class DelegateToModelValidator(object):

    def set_context(self, serializer):
        self.model = serializer.Meta.model

    def __call__(self, attrs):
        obj = self.model(**attrs)
        obj.clean()

class SomeModelSerializer(serializers.ModelSerializer):
    #...
    class Meta:
        model = SomeModel
        validators = (
            DelegateToModelValidator(),
        )

注意事项:


  • 您的模型的额外实例只需调用 clean

  • 您仍然必须将mixin /验证器添加到序列化程序中

这篇关于我应该在哪里做对象和字段的django验证?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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