Detailed usage of django Serializer serialization

  • 2020-12-18 01:51:17
  • OfStack

Serializer serializer

Define Serializer

1. Define methods

Serializer in Django REST framework is defined using a class that inherits from ES16en_framework.serializers.Serializer.

For example, we already have a database model class, BookInfo


class BookInfo(models.Model):
  btitle = models.CharField(max_length=20, verbose_name=' The name of the ')
  bpub_date = models.DateField(verbose_name=' The release date ', null=True)
  bread = models.IntegerField(default=0, verbose_name=' reading ')
  bcomment = models.IntegerField(default=0, verbose_name=' Comment on the amount ')
  image = models.ImageField(upload_to='booktest', verbose_name=' The picture ', null=True)

We want to provide a serializer for this model class, which can be defined as follows:


class BookInfoSerializer(serializers.Serializer):
  """ Book data serializer """
  id = serializers.IntegerField(label='ID', read_only=True)
  btitle = serializers.CharField(label=' The name of the ', max_length=20)
  bpub_date = serializers.DateField(label=' The release date ', required=False)
  bread = serializers.IntegerField(label=' reading ', required=False)
  bcomment = serializers.IntegerField(label=' Comment on the amount ', required=False)
  image = serializers.ImageField(label=' The picture ', required=False)

Note: serializer is not only defined for database model classes, but also for data defined for non-database model classes. serializer exists independently of the database.

2. Fields and options

Common field types:

字段 字段构造方式
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(maxlength=50, min_length=None, allow_blank=False)
正则字段,验证正则模式 [a-zA-Z0-9-]+
URLField URLField(max_length=200, min_length=None, allow_blank=False)
UUIDField UUIDField(format='hex_verbose')
format:
1) 'hex_verbose' 如"5ce0e9a5-5ffa-654b-cee0-1238041fb31a"
2) 'hex' 如 "5ce0e9a55ffa654bcee01238041fb31a"
3)'int' - 如: "123456789012312313134124512351145145114"
4)'urn' 如: "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: 最多位数
decimal_palces: 小数点位置
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与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=)

Option parameters:

参数名称 作用
max_length 最大长度
min_lenght 最小长度
allow_blank 是否允许为空
trim_whitespace 是否截断空白字符
max_value 最小值
min_value 最大值

General parameters:

参数名称 说明
read_only 表明该字段仅用于序列化输出,默认False
write_only 表明该字段仅用于反序列化输入,默认False
required 表明该字段在反序列化时必须输入,默认True
default 反序列化时使用的默认值
allow_null 表明该字段是否允许传入None,默认False
validators 该字段使用的验证器
error_messages 包含错误编号与错误信息的字典
label 用于HTML展示API页面时,显示的字段名称
help_text 用于HTML展示API页面时,显示的字段帮助提示信息

Create the Serializer object

With the Serializer class defined, you are ready to create the Serializer object.

The construction method of Serializer is:


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

Description:

1) When used for serialization, the model class object is passed into the instance parameter

2) When used for deserialization, the data to be deserialized is passed into the data parameter

3) In addition to instance and data parameters, when constructing Serializer objects, additional data can be added through context parameters, such as


serializer = AccountSerializer(account, context={'request': request})

The data attached to the context parameter can be obtained through the context attribute of the Serializer object.

Serialization use

We'll learn about the use of serializers in django shell.


python manage.py shell

1 Basic use

1) First query 1 book object


from booktest.models import BookInfo
book = BookInfo.objects.get(id=2)

2) Construct the serializer object


from booktest.serializers import BookInfoSerializer
serializer = BookInfoSerializer(book)

3) Obtain serialized data

The serialized data can be obtained through the data attribute


serializer.data
# {'id': 2, 'btitle': ' Draco 8 The ministry of ', 'bpub_date': '1986-07-24', 'bread': 36, 'bcomment': 40, 'image': None}

4) If the query set QuerySet contains multiple data to be serialized, you can add the many=True parameter


book_qs = BookInfo.objects.all()
serializer = BookInfoSerializer(book_qs, many=True)
serializer.data
# [OrderedDict([('id', 2), ('btitle', ' Draco 8 The ministry of '), ('bpub_date', '1986-07-24'), ('bread', 36), ('bcomment', 40), ('image', N]), OrderedDict([('id', 3), ('btitle', ' The Legendary Swordsman '), ('bpub_date', '1995-12-24'), ('bread', 20), ('bcomment', 80), ('image'ne)]), OrderedDict([('id', 4), ('btitle', ' Fox Volant of the Snowy Mountain '), ('bpub_date', '1987-11-11'), ('bread', 58), ('bcomment', 24), ('ima None)]), OrderedDict([('id', 5), ('btitle', ' Journey to the west '), ('bpub_date', '1988-01-01'), ('bread', 10), ('bcomment', 10), ('im', 'booktest/xiyouji.png')])]

Nested serialization of associated objects

If the data to be serialized contains other associated objects, the serialization of the associated object data needs to be indicated.

For example, when defining the serializer for hero data, how does the foreign key hbook (that is, the book to which it belongs) field serialize?

Let's start by defining the rest of the HeroInfoSerialzier excluding the key field


class HeroInfoSerializer(serializers.Serializer):
  """ Hero data serializer """
  GENDER_CHOICES = (
    (0, 'male'),
    (1, 'female')
  )
  id = serializers.IntegerField(label='ID', read_only=True)
  hname = serializers.CharField(label=' The name ', max_length=20)
  hgender = serializers.ChoiceField(choices=GENDER_CHOICES, label=' gender ', required=False)
  hcomment = serializers.CharField(label=' Description information ', max_length=200, required=False, allow_null=True)

For associated fields, you can do the following:

1) PrimaryKeyRelatedField

This field will be serialized as the primary key of the associated object.


class BookInfoSerializer(serializers.Serializer):
  """ Book data serializer """
  id = serializers.IntegerField(label='ID', read_only=True)
  btitle = serializers.CharField(label=' The name of the ', max_length=20)
  bpub_date = serializers.DateField(label=' The release date ', required=False)
  bread = serializers.IntegerField(label=' reading ', required=False)
  bcomment = serializers.IntegerField(label=' Comment on the amount ', required=False)
  image = serializers.ImageField(label=' The picture ', required=False)
0

read_only=True or queryset parameter should be included when specifying the field:

This field will not be used for deserialization when the read_only=True parameter is included When the queryset parameter is included, it will be used for deserialization parameter validation

Effect:


class BookInfoSerializer(serializers.Serializer):
  """ Book data serializer """
  id = serializers.IntegerField(label='ID', read_only=True)
  btitle = serializers.CharField(label=' The name of the ', max_length=20)
  bpub_date = serializers.DateField(label=' The release date ', required=False)
  bread = serializers.IntegerField(label=' reading ', required=False)
  bcomment = serializers.IntegerField(label=' Comment on the amount ', required=False)
  image = serializers.ImageField(label=' The picture ', required=False)
1

2) StringRelatedField

This field will be serialized to the string representation of the associated object (that is, the return value of the method with succstr__)


class BookInfoSerializer(serializers.Serializer):
  """ Book data serializer """
  id = serializers.IntegerField(label='ID', read_only=True)
  btitle = serializers.CharField(label=' The name of the ', max_length=20)
  bpub_date = serializers.DateField(label=' The release date ', required=False)
  bread = serializers.IntegerField(label=' reading ', required=False)
  bcomment = serializers.IntegerField(label=' Comment on the amount ', required=False)
  image = serializers.ImageField(label=' The picture ', required=False)
2

Use effect

[

{' id: 6, 'hname' : 'xiao feng', 'hgender: 1,' hcomment ':' dragon 108 zhangs', 'hbook' : 'day dragon 8'}

]

3) HyperlinkedRelatedField

This field will be serialized as an interface link to get the associated object data


hbook = serializers.HyperlinkedRelatedField(label=' The book ', read_only=True, view_name='books-detail')

The view_name parameter must be specified so that DRF finds the route based on the view name and splices it into a complete URL.

Use effect

[

{' id: 6, 'hname' : 'xiao feng', 'hgender: 1,' hcomment ':' dragon 108 zhangs', 'hbook' : 'http: / / 127.0.0.1:8000 / books / 2 /'}

]

We have not yet defined the view, and this will not be demonstrated.

4) SlugRelatedField

This field is serialized into the specified field data of the associated object


class BookInfoSerializer(serializers.Serializer):
  """ Book data serializer """
  id = serializers.IntegerField(label='ID', read_only=True)
  btitle = serializers.CharField(label=' The name of the ', max_length=20)
  bpub_date = serializers.DateField(label=' The release date ', required=False)
  bread = serializers.IntegerField(label=' reading ', required=False)
  bcomment = serializers.IntegerField(label=' Comment on the amount ', required=False)
  image = serializers.ImageField(label=' The picture ', required=False)
4

slug_field specifies which field of the associated object to use

Use effect

[

{'id': 6, 'hname': 'Qiao Feng ': 1, 'hcomment':' Dragon 108 PAWS ', 'hbook': datetime.date(1986, 7, 24)}

]

5) Use the serializer of the associated object


class BookInfoSerializer(serializers.Serializer):
  """ Book data serializer """
  id = serializers.IntegerField(label='ID', read_only=True)
  btitle = serializers.CharField(label=' The name of the ', max_length=20)
  bpub_date = serializers.DateField(label=' The release date ', required=False)
  bread = serializers.IntegerField(label=' reading ', required=False)
  bcomment = serializers.IntegerField(label=' Comment on the amount ', required=False)
  image = serializers.ImageField(label=' The picture ', required=False)
5

Use effect

[

{' id: 6, 'hname' : 'xiao feng', 'hgender: 1,' hcomment ':' dragon 108 zhangs', 'hbook' : OrderedDict ([(' id, 2), (' btitle ', 'day dragon 8) te', '1986-07-24'), (' bread, 36), (40) 'bcomment', 'image' None])}

]

6) Override to_representation method

Each field of the serializer is actually formatted by the to_representation method of that field type, which you can override to determine the format.

Note that the to_representations method is not limited to controlling the associated object format, but applies to individual serializer field types.

Customize 1 new associated field:


class BookInfoSerializer(serializers.Serializer):
  """ Book data serializer """
  id = serializers.IntegerField(label='ID', read_only=True)
  btitle = serializers.CharField(label=' The name of the ', max_length=20)
  bpub_date = serializers.DateField(label=' The release date ', required=False)
  bread = serializers.IntegerField(label=' reading ', required=False)
  bcomment = serializers.IntegerField(label=' Comment on the amount ', required=False)
  image = serializers.ImageField(label=' The picture ', required=False)
6

Specifies that hbook is of type BookRelateField


class BookInfoSerializer(serializers.Serializer):
  """ Book data serializer """
  id = serializers.IntegerField(label='ID', read_only=True)
  btitle = serializers.CharField(label=' The name of the ', max_length=20)
  bpub_date = serializers.DateField(label=' The release date ', required=False)
  bread = serializers.IntegerField(label=' reading ', required=False)
  bcomment = serializers.IntegerField(label=' Comment on the amount ', required=False)
  image = serializers.ImageField(label=' The picture ', required=False)
7

Use effect

[

{'id': 6, 'hname': 'Qiao Feng ', 'hgender': 1, 'hcomment':' Dragon 108 PAWS ', 'hbook': 2 Tianlong 8 '}

]

many parameters

If the associated object data is not only one, but contains multiple data. For example, if you want to serialize the book BookInfo data, each BookInfo object associated with the hero HeroInfo object may have multiple objects. At this time, you can still use the above methods to indicate the associated field type, only add one more many=True parameter when declaring the associated field.

Only the PrimaryKeyRelatedField type is used here as an example, but the rest is the same.

Add associated fields to BookInfoSerializer:


class BookInfoSerializer(serializers.Serializer):
  """ Book data serializer """
  id = serializers.IntegerField(label='ID', read_only=True)
  btitle = serializers.CharField(label=' The name of the ', max_length=20)
  bpub_date = serializers.DateField(label=' The release date ', required=False)
  bread = serializers.IntegerField(label=' reading ', required=False)
  bcomment = serializers.IntegerField(label=' Comment on the amount ', required=False)
  image = serializers.ImageField(label=' The picture ', required=False)
  heroinfo_set = serializers.PrimaryKeyRelatedField(read_only=True, many=True) #  new 

Effect:


class BookInfoSerializer(serializers.Serializer):
  """ Book data serializer """
  id = serializers.IntegerField(label='ID', read_only=True)
  btitle = serializers.CharField(label=' The name of the ', max_length=20)
  bpub_date = serializers.DateField(label=' The release date ', required=False)
  bread = serializers.IntegerField(label=' reading ', required=False)
  bcomment = serializers.IntegerField(label=' Comment on the amount ', required=False)
  image = serializers.ImageField(label=' The picture ', required=False)
9

Related articles: