Django Rest Framework自动处理哪些类型的验证? [英] What types of validations are automatically handled by Django Rest Framework?

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

问题描述

让我们说我有一个定义如下的模型:

Lets say I have a model defined as follows:

from django.core.validators import MinValueValidator, MaxValueValidator, RegexValidator

alphanumeric_validator = RegexValidator(r'^[a-zA-Z0-9]*$', 'Only alphanumeric characters are allowed.')

class Person(model.Model):
    name = models.CharField(max_length=60, validators=[alphanumeric_validator])
    number = models.IntegerField(validators=[MinValueValidator(0), MaxValueValidator(100)])
    email = models.EmailField()

现在,让我说我正在使用Django Rest序列化并创建Person对象框架。看起来像这样:

Now, lets say I am serializing and creating Person objects using Django Rest Framework. It looks like like this:

from rest_framework import serializers
from .models import Person
from rest_framework.response import Response

class PersonSerializer(serializers.ModelSerializer):
    class Meta:
        model = Person
        fields = ('name', 'number', 'email')

class PostPerson(APIView):
    def post(self, request, format=None):
        serializer = PersonSerializer(data=request.data)
        if serializer.is_valid():
            serializer.save()=
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

现在,我的问题是:当我使用验证序列化程序时is_valid(),DRF是否处理 validators = [alphanumeric_validator] validators = [MinValueValidator(0),MaxValueValidator (100)] ?另外,我确定DRF会自动处理 max_length 属性,但是它还会检查 email 是否为实际电子邮件地址使用正确的正则表达式?

Now, my question is this: when I am validating the serializer using is_valid(), does DRF handle the validators=[alphanumeric_validator], and validators=[MinValueValidator(0), MaxValueValidator(100)]? Also, I am sure DRF automatically handles the max_length property, but does it also check if the email is an actual email address using the proper regex?

我通常对clean,full_clean以及在表单验证和序列化程序验证期间调用的所有方法感到困惑,因此想获得一些扎实的解释。

I am generally just confused about clean, full_clean, and all the methods that are called during form validations and serializer validations, so would like to get some solid explanations.

预先感谢。

推荐答案

Django rest框架验证的行为与Django类似 ModelForm 验证;

Django rest framework validation behaves similarly to Django ModelForm validation; it takes the arguments from your models fields and validates accordingly.

例如,我们将使用一个简单的模型&具有字段唯一性约束的序列化器类。

For example we'll take a simple model & serializer class that has a field with a uniqueness constraint.

class CustomerReportRecord(models.Model):
    time_raised = models.DateTimeField(default=timezone.now, editable=False)
    reference = models.CharField(unique=True, max_length=20)


class CustomerReportSerializer(serializers.ModelSerializer):
    class Meta:
        model = CustomerReportRecord

以及当我们打开Django时外壳程序,我们可以看到验证器已应用于序列化程序(注意 max_length validators 列表)

and when we open up Django shell we can see that the validator has been applied to the serializer (notice the max_length and the validators list)

>>> from project.example.serializers import CustomerReportSerializer
>>> serializer = CustomerReportSerializer()
>>> print(repr(serializer))
CustomerReportSerializer():
    id = IntegerField(label='ID', read_only=True)
    time_raised = DateTimeField(read_only=True)
    reference = CharField(max_length=20, validators=[<UniqueValidator(queryset=CustomerReportRecord.objects.all())>])

打印序列化程序实例的 repr 将向您确切显示其适用的验证规则。在模型实例上没有调用任何其他隐藏的验证行为。

Printing the repr of a serializer instance will show you exactly what validation rules it applies. There's no extra hidden validation behaviour being called on the model instance.

当涉及到 .clean .full_clean 方法是验证用户输入数据的另一种方法-将其标准化为一致的格式。当您在表单上而不是在其余框架序列化程序中调用 .is_valid()方法时,这些将以Django形式执行。

When it comes to the .clean and .full_clean methods just another way to validate user input data — normalise it to a consistent format. These are executed in Django forms when you call the .is_valid() method on a form, not in your rest framework serializer.

但是返回REST框架验证器。让我们看一下 Serializer.to_internal_value 方法。

Back to REST framework validators though. Lets take a look at the Serializer.to_internal_value method.

def to_internal_value(self, data):
    """
    Dict of native values <- Dict of primitive datatypes.
    """
    if not isinstance(data, dict):
        message = self.error_messages['invalid'].format(
            datatype=type(data).__name__
        )
        raise ValidationError({
            api_settings.NON_FIELD_ERRORS_KEY: [message]
        })

    ret = OrderedDict()
    errors = OrderedDict()
    fields = self._writable_fields

    for field in fields:
        validate_method = getattr(self, 'validate_' + field.field_name, None)
        primitive_value = field.get_value(data)
        try:
            validated_value = field.run_validation(primitive_value)
            if validate_method is not None:
                validated_value = validate_method(validated_value)
        except ValidationError as exc:
            errors[field.field_name] = exc.detail
        except DjangoValidationError as exc:
            errors[field.field_name] = list(exc.messages)
        except SkipField:
            pass
        else:
            set_value(ret, field.source_attrs, validated_value)

    if errors:
        raise ValidationError(errors)

    return ret

我们在这里可以看到序列化程序调用 field.run_validation 方法,该方法使用模型字段验证器,如果验证失败,它们将引发 DjangoValidationError 。如果成功,它将继续运行任何其他存在的验证器,例如序列化器字段特定的验证器( .validate_< field_name> )。

We can see here that the serializer invokes field.run_validation method, which uses model field validators and they raise a DjangoValidationError if validation fails. If it succeeds it'll continue to run any additional validators that are present such as serializer field specific validators (.validate_<field_name>).

详细了解验证及其在Django&中的工作方式; DRF在这里:

Read up more on validation and how it works in Django & DRF here:


  1. 表单字段验证Django 2.1

  2. 验证者-DRF文档

  3. 序列化程序验证-DRF文档

  4. 验证Django模型的正确方法

  5. DRF序列化程序代码

  1. Form Field Validation Django 2.1
  2. Validators - DRF Docs
  3. Serializer Validation - DRF Docs
  4. Correct way to validate Django Models
  5. DRF Serializer code

希望这有助于了解验证在DRF中的工作原理,即使只是一点点

Hope this helps to understand how validation works in DRF if even by a bit

编辑:只要您的字段在模型中将您存储电子邮件的位置定义为 EmailField ,然后DRF将验证电子邮件。可以在此处

As long as your field that you're storing emails in is defined to be an EmailField in your models then DRF will validate emails. More on that can be found here

这篇关于Django Rest Framework自动处理哪些类型的验证?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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