序列化器 Serializer -- Django




概述


Serializers and ModelSerializers are similar to Forms and ModelForms. Unlike forms, they are not constrained to dealing with HTML output, and form encoded input.

Serialization in REST framework is a two-phase process:

  • 1. Serializers marshal between complex types like model instance, and python primitives.
  • 2. The process of marshaling between python primitives and request and response content is handled by parsers and renderers.


序列化器的作用


  • 序列化: 把模型对象转换成字典, 经过 response 后变成 json 字符串
  • 反序列化: 把客户端发送过来的数据, 经过 request 后变成字典, 序列化器可以把字典转成模型
  • 数据校验: 可以对请求内容和响应内容进行数据校验


  • 序列化: Serializers allow complex data such as querysets and model instances to be converted to native Python datatypes that can then be easily rendered JSON, XML or other content types.
  • 反序列化: Serializers also provide deserialization, allowing parsed data to be converted back into complex types, after first validating the incoming data.
  • 数据校验: 可以对请求内容和响应内容进行数据校验



原理


序列化


把模型对象转换成字典, 经过 response 后变成 json 字符串


反序列化


把客户端发送过来的数据, 经过 request 后变成字典, 序列化器可以把字典转成模型


数据校验


可以对请求内容和响应内容进行数据校验


接口文档


Serializers



ModelSerializer


A `ModelSerializer` is just a regular `Serializer`, except that:

  • A set of default fields are automatically populated.
  • A set of default validators are automatically populated.
  • Default `.create()` and `.update()` implementations are provided.

The process of automatically determining a set of serializer fields based on the model fields is reasonably complex, but you almost certainly don't need to dig into the implementation.

If the `ModelSerializer` class doesn't generate the set of fields that you need you should either declare the extra/differing fields explicitly on the serializer class, or simply use a `Serializer` class.





HyperlinkedModelSerializer



ListSerializer



BaseSerializer



Advanced serializer usage




第三方包





reference