11 serializer component

Time:2021-10-12

Knowledge points: serializer (lower level), modelserializer (key), listmodelserializer (auxiliary group reform)

Why use serialized components?
The objects and queryset types queried in the view cannot be directly returned to the foreground as data, so the serialization component should be used

1. Define serializer

Routing layer urls.py

from django.urls import path, re_path
from .views import users

urlpatterns = [
    path('bookinfo/', users.BookInfo.as_view()),
    re_path('bookinfo/(?P.*)/$', users.BookInfo.as_view()),
]

Model layer: models.py

1.1 definition method

class BookInfo(models.Model):
    PUB_CHOICES = [
        (0, 'Commercial Press'),
        (1, 'people's Publishing House'),
        (2, 'people's Literature Publishing House'),
        (3, 'Writers Publishing House')
    ]
    PWD = models.charfield (max_length = 32, verbose_name = 'password')
    Publisher = models. Integerfield (choices = pub_choices, default = 0, verbose_name = 'publisher')
    Btitle = models.charfield (max_length = 20, verbose_name = 'name')
    bpub_ Date = models.datefield (verbose_name = 'release date', null = true)
    created_ Time = models.datetimefield (auto_now_add = true, verbose_name = "creation time", help_text = 'creation time')
    Bread = models. Integerfield (default = 0, verbose_name = 'reading volume')
    Bcomment = models. Integerfield (default = 0, verbose_name = 'comments')
    Image = models. Imagefield (upload_to ='icon ', verbose_name =' picture ', default ='icon / default. JPG')

    class Meta:
        db_table = 'BookInfo'
        verbose_ Name = 'book information'
        verbose_name_plural = verbose_name

    def __str__(self):
        return '%s' % self.btitle

Provide a serializer for this model class

from rest_framework import serializers

class BookInfoSerializer(serializers.Serializer):
    "" "book data serializer" ""
    id = serializers.IntegerField(label='ID', read_only=True)
    PWD = serializers. Charfield (label = 'password', required = true)
    Publisher = serializers. Integerfield (label = 'publisher')
    Btitle = serializers.charfield (label = 'name', max_length = 20)
    bpub_ Date = serializers.datefield (label = 'release date', required = false)
    created_ Time = serializers.datetimefield (label = 'creation time', required = false)
    Bread = serializers. Integerfield (label = 'reading amount', required = false)
    Bcomment = serializers. Integerfield (label = 'comments', required = false)
    Image = serializers. Imagefield (label = 'picture', required = false)
    """
    Custom serialization properties
    Format: the attribute name is optional, and the value is provided by the fixed naming convention method
    def get_ Property name (self, model object participating in serialization):
        返回值就是Custom serialization properties的值
    """
    #Publisher display name instead of 0, 1...
    publisher_name = serializers.SerializerMethodField()

    def get_publisher_name(self, obj):
        #Interpretive value of choice type get_ Field_ Display()
        return obj.get_publisher_display()

    #The picture shows the full path
    image_path = serializers.SerializerMethodField()

    def get_image_path(self, obj):
        # settings.MEDIA_ URL: self configured / media /, prepared for later advanced serialization and view classes
        #Obj.icon cannot be returned directly as data because although the content is a string, the type is imagefieldfile
        return '%s%s%s' % (r'http://127.0.0.1:8000', settings.MEDIA_URL, str(obj.image))

    #Custom virtual reading volume, increased by 10
    fictitious_bread = serializers.SerializerMethodField()

    def get_fictitious_bread(self, obj):
        return obj.bread + 10

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

1.2 fields and options

Common field types

field Field construction method
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) regular field to verify the regular pattern [a-za-z0-9-]+
URLField URLField(max_length=200, min_length=None, allow_blank=False)
UUIDField UUIDField(format=’hex_verbose’) format: 1) 'hex_verbose'as"5ce0e9a5-5ffa-654b-cee0-1238041fb31a" 2) 'hex'as"5ce0e9a55ffa654bcee01238041fb31a" 3)'int'-For example:"123456789012312313134124512351145145114" 4)'urn'For example:"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 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 are used in the same way as 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:

Parameter name effect
max_length Maximum length: the maximum input length is checked during deserialization
min_lenght Minimum length: the minimum length of input is checked during deserialization
allow_blank Allow null: it is allowed to pass a blank string during deserialization. It is not allowed by default
trim_whitespace Whether to truncate white space characters. The default is true
max_value Maximum value: input maximum value verification is performed during deserialization
min_value Minimum value: input minimum value verification is performed during deserialization

General parameters:

Parameter name explain
read_only Indicates that this field is only used for serialized output. The default is false
write_only Indicates that this field is only used for deserialization input. The default is false
required Indicates that this field must be entered during deserialization. The default is true
default Default value to use when deserializing
allow_null Indicates whether the field is allowed to pass in none. The default is false
validators Validator used by this field
error_messages A dictionary containing error numbers and error messages
label The name of the field to be displayed when displaying API pages in HTML
help_text It is used to display field help prompt information when HTML displays API pages

1.3 creating serializer objects

After defining the serializer class, you can create the serializer object.

The construction method of serializer is:

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

explain:

1) When used for serialization, the model class object is passed ininstanceparameter

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

3) In addition to the instance and data parameters, you can also use thecontextAdd additional data to parameters, such as

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

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

  1. When using a serializer, we must note that after the serializer is declared, it will not be executed automatically. We need to call it in the view

  2. The serializer cannot directly receive data. We need to pass the data used when creating the serializer object in the view. (data, instance pass parameter)

    ​ Serialization is to find out the data object from the database throughinstanceIn the incoming serializer, the serialized data can be passed to the front end only through the data attribute, not directly to the serialized object
    ​ Deserialization is: data isrequest.dataGet the data from the front end, pass the data into the serializer for verification, and save it to the database

  3. The field declaration of the serializer is similar to the form system we used earlier

  4. When developing the restful API, the serializer will help us convert the model data into a dictionary.

  5. The view provided by DRF will help us convert the dictionary into JSON, or convert the data sent by the client into a dictionary

2. Use of serializer

The serializer is used in two phases:

  1. When requested by the client, the serializer can be used to deserialize the data.
  2. When the server responds, the serializer can be used to serialize the data.
from .. import models
from ..serializers import BookInfoSerializer


class BookInfo(APIView):
    def get(self, request, *args, **kwargs):
        pk = kwargs.get('pk')
        if pk:
            try:
                #1) find the book object
                book_obj = models.BookInfo.objects.get(pk=pk)
                #2) construct serializer
                book_ser = BookInfoSerializer(book_obj)
                #3) get serialized data
                return Response({
                    'status': 200,
                    'msg': 0,
                    #If there is no. Data when serializing, it must be. Data when passing to the front end
                    'results': book_ Ser.data # can obtain the serialized data through the data attribute
                })
            except:
                return Response({
                    'status': 201,
                    'msg ':' book information does not exist ',
                })
        else:
            #1) find the book object:对象列表(queryset)不能直接作为数据返回给前台
            book_obj_list = models.BookInfo.objects.all()
            #2) construct serializer   PS:将对象交给序列化处理,产生序列化对象,如果序列化的数据是由[]嵌套,一定要设置many=True
            book_ser_data = BookInfoSerializer(book_obj_list, many=True)
            #3) get serialized data
            return Response({
                'status': 200,
                'msg': 0,
                'results': book_ ser_ Data.data # can obtain the serialized data through the data attribute
            })

3. Use of deserialization

3.1 verification

  • When using serializer for deserialization, you need to validate the data before you can obtain the successfully validated data or save it as a model class object.
  • Before getting deserialized data, you must callis_valid()Method. If the verification is successful, it returns true. Otherwise, it returns false.
    • If the validation fails, you can use the of the serializer objecterrorsProperty to get the error information and return the dictionary, including the field and the error of the field. If it is a non field error, you can modify the field in the rest framework configurationNON_FIELD_ERRORS_KEYTo control the key names in the error dictionary.
    • The validation is successful and can be passed through the serializer objectvalidated_dataProperty to get data.
  • When defining the serializer, indicating the serialization type and option parameters of each field is itself a verification behavior.

3.2 usage

  1. Which fields must be deserialized
  2. What are the security checks for fields
  3. Which fields need additional check hook functions
  4. Which fields have joint verification
  5. Note: the deserialization fields are used for warehousing. There will be no user-defined method attributes, and there will be user-defined attributes that can set verification rules, which will not be entered into the database
class BookInfoDeSerializer(serializers.Serializer):
    "" "Book serializer" ""
    id = serializers.IntegerField(label='ID', read_only=True)
    PWD = serializers. Charfield (label = 'password', required = true)
    Publisher = serializers. Integerfield (label = 'publisher', required = false)
    Btitle = serializers.charfield (label = 'name', max_length = 20, validators = [about_django])
    bpub_ Date = serializers.datefield (label = 'release date', required = false)
    created_ Time = serializers.datetimefield (label = 'creation time', required = false)
    Bread = serializers. Integerfield (label = 'reading amount', required = true)
    Bcomment = serializers. Integerfield (label = 'comments', required = true)
    Image = serializers. Imagefield (label = 'picture', required = false)

    #Customize the deserialization field with verification rules, such as the confirm password field re_ pwd
    re_pwd = serializers.CharField(required=True)

3.3 verification

3.3.1 is_valid

Validate by constructing the serializer object and passing the data to be deserialized to the data construction parameter

Class bookinfo (apiview): # single addition
    def post(self, request, *args, **kwargs):
        request_data = request.data
        if not isinstance(request_data, dict) or request_data == {}:
            return Response({
                'status': 1,
                'msg ':' data error ',
            })

        book_ser = BookInfoDeSerializer(data=request_data)
        
        #Serialize object call is_ Valid() completes the verification, and the failure information of verification failure will be stored in the serialized object. Errors
        #Inspect whether it is qualified_ Exception = true is required
        book_ser.is_valid(raise_exception=True)
        # book_ Result is an object, and group addition is a list of objects
        book_obj = book_ser.save()
        return Response({
            'status': 200,
            'msg': 'ok',
            'results': BookInfoSerializer(instance=book_obj).data
        })
		The above two sentences are the same as the following
        # if book_ser.is_valid():
        #The # verification is passed and the addition is completed
        #     book_obj = book_ser.save()
        #     return Response({
        #         'status': 0,
        #         'msg': 'ok',
        #         'results': BookInfoSerializer(instance=book_obj).data
        #     })
        # else:
        ## verification failed
        #     return Response({
        #         'status': 1,
        #         'msg': book_ser.errors,
        #     })

is_ The valid () method can also throw an exception serializers. Validationerror when validation fails

Can be passedraise_exception=TrueWhen the parameter is enabled, the rest framework receives this exception and returns an HTTP 400 bad request response to the front end.

# Return a 400 response if the data was invalid.
serializer.is_valid(raise_exception=True)

If it is not enough, you can use the following three methods to define the verification behavior

3.3.2 validate_-Local hook

  • yesField

  • Local hook: validate_ Name of the field to be verified (self, the value of the current field to be verified)

  • Verification rules: the original value is returned after verification. If verification fails, an exception is thrown

class BookInfoSerializer(serializers.Serializer):
    "" "book data serializer" ""
    ...
    
	#Local hook: validate_ Name of the field to be verified (self, the value of the current field to be verified)
    #Verification rules: the original value is returned after verification. If verification fails, an exception is thrown
    def validate_btitle(self, value):
        if 'django' not in value.lower():
            Raise exceptions. Validationerror ('the book is not about Django ')
        return value

test

http://127.0.0.1:8000/bookinfo/
{
    "Btitle": "a dream of Red Mansions",
    "bpub_date":"2020-10-07"
}

{
    "btitle": [
        "Books are not about Django"
    ]
}

3.3.2 validate – global hook

  • When multiple fields need to be compared and verified at the same time in the serializer, you can define the validate method to verify

  • Global hook: validate (self, all data after system and local hook verification)

class BookInfoSerializer(serializers.Serializer):
    "" "book data serializer" ""
    ...   
    #Global hook: validate (self, all data after system and local hook verification)
    Def validate (self, attrs): # attrs is the dictionary format
        pwd = attrs.get('pwd')
        re_ PWD = attrs.pop ('re_pwd ') # because re_ PWD does not need to be stored in the database, so delete this field in the global hook verification
        bread = attrs['bread']
        bcomment = attrs['bcomment']
        if pwd != re_pwd:
            Raise exceptions. Validationerror ({'pwd&re_pwd': 'two passwords are inconsistent'})
        if bread < bcomment:
            Raise serializers. Validationerror ('reads less than comments')
        return attrs

3.3.3 validators

  • Add the validators option parameter in the field to supplement the validation behavior
def about_django(value):
    if 'django' not in value.lower():
        Raise serializers. Validationerror ("validators - books are not about Django")

class BookInfoDeSerializer(serializers.Serializer):
    id = serializers.IntegerField(label='ID', read_only=True)
    PWD = serializers. Charfield (label = 'password', required = true)
    Publisher = serializers. Integerfield (label = 'publisher', required = false)
    Btitle = serializers.charfield (label = 'name', max_length = 20, validators = [about_django])
    bpub_ Date = serializers.datefield (label = 'release date', required = false)
    created_ Time = serializers.datetimefield (label = 'creation time', required = false)
    Bread = serializers. Integerfield (label = 'reading amount', required = true)
    Bcomment = serializers. Integerfield (label = 'comments', required = true)
    Image = serializers. Imagefield (label = 'picture', required = false)

Test:

Copyfrom booktest.serializers import BookInfoSerializer
data = {'btitle': 'python'}
serializer = BookInfoSerializer(data=data)
serializer.is_valid()  # False   
serializer.errors
#{'btitle': [errordetail (string = 'the book is not about Django', code ='Invalid ')]}

3.3.4 validators、validate_. validate priority

validators—>validate_(local) —- > validate (global)

3.4 deserialization – save data

If you want to be based on validated after successful validation_ Data completes the creation of data objects, which can be realized by implementing the create () and update () methods.

class BookInfoSerializer(serializers.Serializer):
    "" "book data serializer" ""
    ...
    
    #To complete the addition, you must override the Create method, validated_ Data is the verified data
    def create(self, validated_data):
        #Try to store data directly after all verification rules are completed
        return models.User.objects.create(**validated_data)
    
    def update(self, instance, validated_data):
        "" "update, instance is the object instance to be updated" ""
        instance.btitle = validated_data.get('btitle', instance.btitle)
        instance.bpub_date = validated_data.get('bpub_date', instance.bpub_date)
        instance.pwd = validated_data.get('pwd', instance.pwd)
        instance.bread = validated_data.get('bread', instance.bread)
        instance.bcomment = validated_data.get('bcomment', instance.bcomment)
        return instance

If you need to save the data to the database when returning the data object, you can modify it as follows

class BookInfoSerializer(serializers.Serializer):
    "" "book data serializer" ""
    ...

    def create(self, validated_data):
        "" "new" ""
        return BookInfo.objects.create(**validated_data)

    def update(self, instance, validated_data):
        "" "update, instance is the object instance to be updated" ""
        instance.btitle = validated_data.get('btitle', instance.btitle)
        instance.bpub_date = validated_data.get('bpub_date', instance.bpub_date)
        instance.bread = validated_data.get('bread', instance.bread)
        instance.bcomment = validated_data.get('bcomment', instance.bcomment)
        instance.save()
        return instance

After implementing the above two methods, when deserializing data, you can return a data object instance through the save () method

book = serializer.save()

If the instance instance is not passed when creating the serializer object, create () is called when the save () method is called. On the contrary, if the instance is passed, update () is called when the save () method is called.

models.py

from django.db import models

class BookInfo(models.Model):
    PUB_CHOICES = [
        (0, 'Commercial Press'),
        (1, 'people's Publishing House'),
        (2, 'people's Literature Publishing House'),
        (3, 'Writers Publishing House')
    ]
    PWD = models.charfield (max_length = 32, verbose_name = 'password')
    Publisher = models. Integerfield (choices = pub_choices, default = 0, verbose_name = 'publisher')
    Btitle = models.charfield (max_length = 20, verbose_name = 'name')
    bpub_ Date = models.datefield (verbose_name = 'release date', null = true)
    created_ Time = models.datetimefield (auto_now_add = true, verbose_name = "creation time", help_text = 'creation time')
    Bread = models. Integerfield (default = 0, verbose_name = 'reading volume')
    Bcomment = models. Integerfield (default = 0, verbose_name = 'comments')
    Image = models. Imagefield (upload_to ='icon ', verbose_name =' picture ', default ='icon / default. JPG')

    class Meta:
        db_table = 'BookInfo'
        verbose_ Name = 'book information'
        verbose_name_plural = verbose_name

    def __str__(self):
        return '%s' % self.btitle

Routing: URLs

from django.urls import path, re_path
from .views import test, users, books, v2books

urlpatterns = [
    path('bookinfo/', users.BookInfo.as_view()),
    re_path('bookinfo/(?P.*)/$', users.BookInfo.as_view()),
]

Views view

rom rest_framework.views import APIView
from rest_framework.response import Response

from .. import models
from ..serializers import UserSerializer, UserDeserializer, BookInfoSerializer, BookInfoDeSerializer


class BookInfo(APIView):
    def get(self, request, *args, **kwargs):
        pk = kwargs.get('pk')
        if pk:
            try:
                #1) find the book object
                book_obj = models.BookInfo.objects.get(pk=pk)
                #2) construct serializer
                book_ser = BookInfoSerializer(instance=book_obj)
                #3) get serialized data
                return Response({
                    'status': 200,
                    'msg': 0,
                    'results': book_ Ser.data # can obtain the serialized data through the data attribute
                })
            except:
                return Response({
                    'status': 201,
                    'msg ':' book information does not exist ',
                })
        else:
            #1) find the book object
            book_obj_list = models.BookInfo.objects.all()
            #2) construct serializer   PS:如果要被序列化的是包含多条数据的查询集QuerySet,可以通过添加many=True参数补充说明
            book_ser_data = BookInfoSerializer(instance=book_obj_list, many=True)
            #3) get serialized data
            return Response({
                'status': 200,
                'msg': 0,
                'results': book_ ser_ Data.data # can obtain the serialized data through the data attribute
            })

    def post(self, request, *args, **kwargs):
        request_data = request.data
        if not isinstance(request_data, dict) or request_data == {}:
            return Response({
                'status': 1,
                'msg ':' data error ',
            })

        book_ser = BookInfoDeSerializer(data=request_data)
        #Serialize object call is_ Valid() completes the verification, and the failure information of verification failure will be stored in the serialized object. Errors
        #Inspect whether it is qualified_ Exception = true is required
        book_ser.is_valid(raise_exception=True)
        # book_ Result is an object, and group addition is a list of objects
        book_obj = book_ser.save()
        return Response({
            'status': 200,
            'msg': 'ok',
            'results': BookInfoSerializer(instance=book_obj).data
        })

        # if book_ser.is_valid():
        #The # verification is passed and the addition is completed
        #     book_obj = book_ser.save()
        #     return Response({
        #         'status': 0,
        #         'msg': 'ok',
        #         'results': BookInfoSerializer(instance=book_obj).data
        #     })
        # else:
        ## verification failed
        #     return Response({
        #         'status': 1,
        #         'msg': book_ser.errors,
        #     })

serializers.py

from rest_framework import serializers
from django.conf import settings
from rest_framework.exceptions import ValidationError
from . import models

#Serialization
class BookInfoSerializer(serializers.Serializer):
    "" "book data serializer" ""
    id = serializers.IntegerField(label='ID', read_only=True)
    PWD = serializers. Charfield (label = 'password', required = true)
    Publisher = serializers. Integerfield (label = 'publisher', required = false)
    Btitle = serializers.charfield (label = 'name', max_length = 20)
    bpub_ Date = serializers.datefield (label = 'release date', required = false)
    created_ Time = serializers.datetimefield (label = 'creation time', required = false)
    Bread = serializers. Integerfield (label = 'reading amount', required = false)
    Bcomment = serializers. Integerfield (label = 'comments', required = false)
    Image = serializers. Imagefield (label = 'picture', required = false)
    """
    Custom serialization properties
    Format: the attribute name is optional, and the value is provided by the fixed naming convention method
    def get_ Property name (self, model object participating in serialization):
        返回值就是Custom serialization properties的值
    """
    #Publisher display name instead of 0, 1...
    publisher_name = serializers.SerializerMethodField()

    def get_publisher_name(self, obj):
        #Interpretive value of choice type get_ Field_ Display()
        return obj.get_publisher_display()

    #The picture shows the full path
    image_path = serializers.SerializerMethodField()

    def get_image_path(self, obj):
        # settings.MEDIA_ URL: self configured / media /, prepared for later advanced serialization and view classes
        #Obj.icon cannot be returned directly as data because although the content is a string, the type is imagefieldfile
        return '%s%s%s' % (r'http://127.0.0.1:8000', settings.MEDIA_URL, str(obj.image))

    #Custom virtual reading volume, increased by 10
    fictitious_bread = serializers.SerializerMethodField()

    def get_fictitious_bread(self, obj):
        return obj.bread + 10


def about_django(value):
    if 'django' not in value.lower():
        Raise serializers. Validationerror ("validators - books are not about Django")

#Deserialization
class BookInfoDeSerializer(serializers.Serializer):
    id = serializers.IntegerField(label='ID', read_only=True)
    PWD = serializers. Charfield (label = 'password', required = true)
    Publisher = serializers. Integerfield (label = 'publisher', required = false)
    Btitle = serializers.charfield (label = 'name', max_length = 20, validators = [about_django])
    bpub_ Date = serializers.datefield (label = 'release date', required = false)
    created_ Time = serializers.datetimefield (label = 'creation time', required = false)
    Bread = serializers. Integerfield (label = 'reading amount', required = true)
    Bcomment = serializers. Integerfield (label = 'comments', required = true)
    Image = serializers. Imagefield (label = 'picture', required = false)

    #Customize the deserialization field with verification rules, such as the confirm password field re_ pwd
    re_pwd = serializers.CharField(required=True)

    #Local hook: validate_ Name of the field to be verified (self, the value of the current field to be verified)
    #Verification rules: the original value is returned after verification. If verification fails, an exception is thrown
    def validate_btitle(self, value):
        if 'django' not in value.lower():
            Raise exceptions. Validationerror ('validate_btitle - books are not about Django ')
        return value

    #Global hook: validate (self, all data after system and local hook verification)
    Def validate (self, attrs): # attrs is the dictionary format
        pwd = attrs.get('pwd')
        re_ PWD = attrs.pop ('re_pwd ') # because re_ PWD does not need to be stored in the database, so delete this field in the global hook verification
        bread = attrs['bread']
        bcomment = attrs['bcomment']
        if pwd != re_pwd:
            Raise exceptions. Validationerror ({'pwd&re_pwd': 'two passwords are inconsistent'})
        if bread < bcomment:
            Raise serializers. Validationerror ('reads less than comments')
        return attrs

    #To complete the addition, you must override the Create method, validated_ Data is the verified data
    def create(self, validated_data):
        #Try to store data directly after all verification rules are completed
        return models.User.objects.create(**validated_data)

    def update(self, instance, validated_data):
        "" "update, instance is the object instance to be updated" ""
        instance.btitle = validated_data.get('btitle', instance.btitle)
        instance.bpub_date = validated_data.get('bpub_date', instance.bpub_date)
        instance.pwd = validated_data.get('pwd', instance.pwd)
        instance.bread = validated_data.get('bread', instance.bread)
        instance.bcomment = validated_data.get('bcomment', instance.bcomment)
        return instance

3.5 additional instructions

1) When saving the serializer with save (), additional data can be passed, which can be validated in create () and update ()_ Data parameter obtained

#Request. User is a model object in Django that records the currently logged in user
serializer.save(owner=request.user)

2) The default serializer must pass all required fields, otherwise a validation exception will be thrown. However, we can use the partial parameter to allow partial field updates

# Update `comment` with partial data
serializer = CommentSerializer(comment, data={'content': u'foo bar'}, partial=True)