简体   繁体   English

如何在 Django REST 中使用验证器方法验证模型字段?

[英]How to validate model field using validator method in Django REST?

I want to validate email while saving an object through API.我想在通过 API 保存对象的同时验证电子邮件。 I'm using model validate but it's not working while saving Invitation object through API, It's working only when we creating objects through the admin panel.我正在使用模型验证,但它在通过 API 保存邀请对象时不起作用,只有当我们通过管理面板创建对象时它才起作用。

models.py模型.py

def validate_email(value): 
    if "@gmail.com" in value: 
        return value 
    else: 
        raise ValidationError("This field accepts mail id of google only") 


class Invitation(models.Model):
    email = models.EmailField(validators=[validate_email])

The Django documentation says: Django 文档说:

Note that validators will not be run automatically when you save a model, but if you are using a ModelForm, it will run your validators on any fields that are included in your form请注意,当您保存模型时,验证器不会自动运行,但如果您使用的是 ModelForm,它将在表单中包含的任何字段上运行您的验证器

and the DRF docs says:DRF 文档说:

With REST framework the validation is performed entirely on the serializer class使用 REST 框架,验证完全在序列化器类上执行

Which means in order to validate a model instance creation via api, you will need to define all validations in the Serializer class tself.这意味着为了通过 api 验证模型实例的创建,您需要在 Serializer 类中定义所有验证。

尝试通过Model.clean()对其进行验证

Note that validators will not be run automatically when you save a model, but if you are using a ModelForm, it will run your validators on any fields that are included in your form.请注意,当您保存模型时,验证器不会自动运行,但如果您使用的是 ModelForm,它将在表单中包含的任何字段上运行您的验证器。

Use serializers to validate model properties.使用序列化程序来验证模型属性。 https://www.django-rest-framework.org/api-guide/serializers/#validation https://www.django-rest-framework.org/api-guide/serializers/#validation

serializers.py序列化程序.py

from rest_framework import serializers
class Invitation(serializers.Serializer):
    email = models.EmailField()


    def validate_email(self, value):
        if "@gmail.com" in value: 
            return value 
        else: 
            raise ValidationError("This field accepts mail id of google only") 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM