DRF serializer

Serializer -Serializer

effect:

1. 序列化,序列化器会把模型对象转换成字典,经过response以后变成json字符串
2. 反序列化,把客户端发送过来的数据,经过request以后变成字典,序列化器可以把字典转成模型
3. 反序列化,完成数据校验功能

Defined serializer

Django REST framework in Serializer uses classes to define, must be inherited from rest_framework.serializers.Serializer.

First, create a sub-application sers

python manage.py startapp sers

Create a blog using the database model class students / Student, code is as follows:

from django.db import models

# Create your models here.
class Student(models.Model):
    # 模型字段
    name = models.CharField(max_length=100,verbose_name="姓名",help_text="提示文本:账号不能为空!")
    sex = models.BooleanField(default=True,verbose_name="性别")
    age = models.IntegerField(verbose_name="年龄")
    class_null = models.CharField(max_length=5,verbose_name="班级编号")
    description = models.TextField(verbose_name="个性签名")

    class Meta:
        db_table="tb_student"
        verbose_name = "学生"
        verbose_name_plural = verbose_name

If you want to provide a serializer for this model class, also you need to create a serializers.py file, then defined as follows:

from rest_framework import serializers

# 声明序列化器,所有的序列化器都要直接或者间接继承于 Serializer
# 其中,ModelSerializer是Serializer的子类,ModelSerializer在Serializer的基础上进行了代码简化
class StudentSerializer(serializers.Serializer):
    """学生信息序列化器"""
    # 1. 需要进行数据转换的字段
    id = serializers.IntegerField()
    name = serializers.CharField()
    age = serializers.IntegerField()
    sex = serializers.BooleanField()
    description = serializers.CharField()

    # 2. 如果序列化器集成的是ModelSerializer,则需要声明调用的模型信息

    # 3. 验证代码

    # 4. 编写添加和更新模型的代码

[Note] serializer is not only for the database model class definition, you can also define non-database data model class. It can be said serializer is independent of the existence of the database.

Common field types

Field

Field Field configuration mode serializers. Configured mode field ()
BooleanField BooleanField()
NullBooleanField NullBooleanField()
CharField CharField(max_length=None, min_length=None, allow_blank=False, trim_whitespace=True)
EmailField EmailField(max_length=None, min_length=None, allow_blank=False)
RegexField RegexField(regex, max_length=None, min_length=None, allow_blank=False)
SlugField SlugField (max * length = 50, min_length = None, allow_blank = False) regular field, to verify normal mode [a-zA-Z0-9 * -] +
URLField URLField(max_length=200, min_length=None, allow_blank=False)
UUIDField UUIDField (= the format 'hex_verbose') the format:
. 1) 'hex_verbose'As "5ce0e9a5-5ffa-654b-cee0-1238041fb31a"
2) 'hex'As "5ce0e9a55ffa654bcee01238041fb31a"
3) 'int'- such as: "123456789012312313134124512351145145114"
4) 'urn'as:"urn:uuid:5ce0e9a5-5ffa-654b-cee0-1238041fb31a"
IPAddressField IPAddressField(protocol='both', unpack_ipv4=False, **options)
IntegerField IntegerField(max_value=None, min_value=None)
FloatField FloatField(max_value=None, min_value=None)
DecimalField DecimalField (max_digits, decimal_places, coerce_to_string = None, MAX_VALUE = None, MIN_VALUE = None)
max_digits: maximum number of digits
decimal_palces: decimal point position
DateTimeField DateTimeField(format=api_settings.DATETIME_FORMAT, input_formats=None)
DateField DateField(format=api_settings.DATE_FORMAT, input_formats=None)
TimeField TimeField(format=api_settings.TIME_FORMAT, input_formats=None)
DurationField DurationField()
ChoiceField ChoiceField (choices) choices and usage of the same Django
MultipleChoiceField MultipleChoiceField(choices)
FileField FileField(max_length=None, allow_empty_file=False, use_url=UPLOADED_FILES_USE_URL)
ImageField ImageField(max_length=None, allow_empty_file=False, use_url=UPLOADED_FILES_USE_URL)
ListField ListField(child=, min_length=None, max_length=None)
DictField DictField(child=)

parameter

parameter name effect
max_length The maximum length
min_lenght The minimum length
allow_blank Whether to allow empty
trim_whitespace Whether or not cut blank character
max_value The maximum value
min_value The minimum value

General parameters

parameter name Explanation
read_only Indicates that the sequence of output fields are used, default False
write_only This field is only used to indicate deserialization input, default False
required Indicates that the field must be entered at the time of deserialization, default True
default The default values ​​used when deserialization
allow_null It indicates whether the field allows incoming None, default False
validators This field is used to verify
error_messages It contains an error number and the error message dictionary
label Field Name HTML for display when the API page, displayed
help_text When the display API for HTML page, field displays help information

Objects created Serializer

After the definition of a good Serializer class, you can create a Serializer objects. Views.py objects can be created in this application in:

Serializer constructor method:

Serializer(instance=None, data=empty, **kwarg)

Description:

1) is used to serialize the incoming class object model instance parameters

2)用于反序列化时,将要被反序列化的数据传入data参数

3)除了instance和data参数外,在构造Serializer对象时,还可通过context参数额外添加数据,如

serializer = StudentSerializer(instance, context={'request': request})
  # 参数instance ,模型对象,这个参数一般用于把模型转成字典,进行序列化
  # 参数data,客户端提交的字典数据,这个参数一般用于把字典转成模型对象,进行校验数据和反序列化
  # 参数context,有时候,路由或者视图中有些数据需要传递序列化器内部的方法中调用,则可以context以字典的格式传递进行
  # 额外参数: many=True, 表示instance是一个模型列表,此时序列化器在转换数据的时候可以进行循环

通过context参数附加的数据,可以通过Serializer对象的context属性获取。

  1. 使用序列化器的时候一定要注意,序列化器声明了以后,不会自动执行,需要我们在视图中进行调用才可以;
  2. 序列化器无法直接接收数据,需要我们在视图中创建序列化器对象时把使用的数据传递过来;
  3. 序列化器的字段声明类似于我们前面使用过的表单系统;
  4. 开发restful api时,序列化器会帮我们把模型数据转换成字典;
  5. drf提供的视图会帮我们把字典转换成json,或者把客户端发送过来的数据转换字典。

Guess you like

Origin www.cnblogs.com/jjzz1234/p/11806292.html