This is the 13th day of my participation in the November Gwen Challenge. Check out the event details: The last Gwen Challenge 2021

How serialization components work

  1. Serialization, the serializer converts the model object into a dictionary, which becomes a JSON string in response
  2. Deserialization, which converts the data sent by the client into a dictionary through request, can be converted into a model by the serializer
  3. Deserialization, complete data verification function

Simple use of serializer for serialization component

  • Write a serialized class

  • Write the fields you want to serialize in the class, and write the fields you want to serialize in the class

  • Import the serialized class into the view class, instantiate the serialized class to get the serialized class’s objects, and pass in the objects that need serialization

  • Data is a dictionary

  • Return the dictionary, and if you don’t use the Response provided by rest_framework, you use JsonResponse

The serialization component uses — serialization to query the interface with the specified ID

  • Prepare a book list
from django.db import models


class Book(models.Model) :
    name = models.CharField(max_length=32)
    price = models.DecimalField(max_digits=8,decimal_places=2)
    publish = models.CharField(max_length=32)

Copy the code
  • Create a py file of any name in which to create a serialized class that inherits APIView from rest_framework.views import APIView

    from rest_framework import seriaizers

    class BookSerializer(serializers.Serializer):

    id = serializers.CharField()
    
    price = serializers.CharField()
    
    publish = serializers.CharField()
    Copy the code
  • Create a view class in views.py, serialize the data using a custom serialization class, and return the data using the Response of the Rest_framework

from app01.ser import BookSerializer
from app01 import models


class BookView(APIView) :
    def get(self,request,pk) :
        dic = {'code':100.'status':'success'}
        book = models.Book.objects.filter(pk=pk).first()
        book_ser = BookSerializer(book)
        dic['data'] = book_ser.data
        return Response(dic)
Copy the code
  • Map routes to view classes in urls.py
re_path(r'^book/(? P
      
       \d+)'
      ,views.BookView.as_view()),
Copy the code

The serialization component uses deserialization to modify data

  • Validation rules need to be defined in the serialized class. If the data returned by the client to the back end meets the validation rules, the data needs to be saved to the database. When the data passes validation, if you do not override the UPDATE method in the serialized class, an exception will be thrown
Serialize the class file
from rest_framework import serializers
from rest_framework.exceptions import ValidationError

Validators =[check_book,] validators=[check_book,] validators=[check_book,
def check_book(data) :
    # data is the name of the corresponding field passed by the browser client, since this method is appended to the name field
    print(data)
    
    
class BookSerializer(serializers.Serializer) :
    id = serializers.CharField(read_only=True)
    name = serializers.CharField(validators=[check_book,])
    price = serializers.CharField()
    publish = serializers.CharField()
    # Partial validation, applicable to a single field
    def validate_name(self, instance) :
        # instance is the data returned by the browser to modify
        if instance.startswith('xxx') :raise ValidationError('Cannot begin with XXX')
        else:
            return instance
    # Global checksum, applicable to checksum of multiple fields
    def validate(self, attrs) :
        Attrs is the data object that the client returns to the back end
        if attrs.get('name') == attrs.get('publish') :raise ValidationError(They can't be the same.)
        else:
            return attrs
    # Override update method
    def update(self, instance, validated_data) :
        ":param instance: modified object :param validATED_data: updated data: return:"
        instance.name = validated_data.get('name')
        instance.price = validated_data.get('price')
        instance.publish = validated_data.get('publish')
        return instance
    
View file
class BookView(APIView) :. .def put(self,request,pk) :
        dic = {'code':100.'status':' '}
        book = models.Book.objects.filter(pk=pk).first()
        # instance is the modified object, and data is the data returned by the browser client
        book_ser = BookSerializer(instance=book,data=request.data)
        Check whether the data is verified
        if book_ser.is_valid():
            The update method needs to be overridden in the serialized class if the data passes validation
            book_ser.save()
            dic['status'] = 'Modified successfully'
            dic['data'] = book_ser.data
        else:
            dic['status'] = 'Modification failed'
            dic['data'] = book_ser.errors
        return Response(dic)
Copy the code

Delete the data

Data is deleted without using a serialization component

def delete(self,request,pk) :
    dic = {'code':100.'status':' '}
    book = models.Book.objects.filter(pk=pk).delete()
    dic['status'] = 'Deleted successfully'
    return Response(dic)
Copy the code

Serialize query all data

When serializing data, you need to specify many=True because there are multiple numbers of data to be retrieved

def get(self,request) :
    books = models.Book.objects.all()
    book_ser = BookSerializer(books,many=True)
    return Response(book_ser.data)
Copy the code

Deserialization — Add new data

The new book needs to be validated by the serialized class and the create method needs to be overridden

# serialize class
    # Override update method
    def update(self, instance, validated_data) :
        ":param instance: modified object :param validATED_data: updated data: return:"
        instance.name = validated_data.get('name')
        instance.price = validated_data.get('price')
        instance.publish = validated_data.get('publish')
        return instance

    def create(self,validated_data) :
        The new data added to the client is a dictionary
        print(validated_data)
        instance = models.Book.objects.create(**validated_data)
        return instance
    
    # views.py
    def post(self,request) :
        Data is the user data object returned by the client to the server
        dic = {'code':100.'status':' '}
        book_ser = BookSerializer(data=request.data)
        if book_ser.is_valid():
            book_ser.save()
            book_ser.save()
            dic['data'] = book_ser.data
        else:
            dic['data'] = book_ser.errors
        return Response(dic)
Copy the code

Model class serializer

class BookModelSerializer(serializers.ModelSerializer) :
    class Meta:
        model=Book  # correspond to the model in models.py
        fields='__all__'  # All fields in models
        # fields = (' name 'and' price ', 'id', 'author') # serialization only the specified field
        # exclude=('name',) # exclude=('name',) # exclude=('name',
        # read_only_fields=('price',)
        # write_only_fields=('id',) # deprecated, uses extra_kwargs
        extra_kwargs = {  Name =serializers.CharField(max_length=16,min_length=4)
            'price': {'write_only': True}},# Other uses are exactly the same
No need to rewrite the create and updata methods
Copy the code

Many = True?

Pass many=True when serializing multiple sets of data.

book_ser=BookModelSerializer(books,many=True)
book_one_ser=BookModelSerializer(book)
print(type(book_ser))
#<class 'rest_framework.serializers.ListSerializer'>
print(type(book_one_ser))
#<class 'app01.ser.BookModelSerializer'>

"' the generation of object -" call first class __new__ method, to generate an empty object = class name (name = LQZ), triggering the __init__ () class __new__ method control object generated ' ' '
def __new__(cls, *args, **kwargs) :
    if kwargs.pop('many'.False) :return cls.many_init(*args, **kwargs)
    # no pass many=True, go below, normal object instantiation
    return super().__new__(cls, *args, **kwargs)
Copy the code

Serializer Advanced usage

# Use of source
	1* * * * * * * * =serializers.CharField(source='title')
    2Publish =serializers.CharField(source='publish.email')
    3You can use the method pub_date=serializers.CharField(source=) in the models table'test'Test is a method in the Book table model# SerializerMethodField() is used when table relationships are many-to-many relationships for fieldsIt needs to have a matching method, the method named get_ field name, the return value is to display the authors = serializers. SerializerMethodField ()It needs a companion method called get_ field name, and the return value is the data to be serialized
    def get_authors(self,instance) :
        # book object
        authors=instance.authors.all(a)# fetch all authors
        l = []
        for author in authors:
            l.append({'name':author.name,'age':author.age})
        return l
Copy the code

Simply encapsulate the status code information returned by the Response object

class MyResponse() :
    def __init__(self) :
        self.status=100
        self.msg='success'
    @property
    def get_dict(self) :
        return self.__dict__

if __name__ == '__main__':
    res=MyResponse()
    res.status=101
    res.msg='Query failed'
    # res.data={'name':'lqz'}
    print(res.get_dict)
Copy the code

supplement

  • The field type of the serialized class
field Field construction
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) Specifies the regular field to verify the regular mode-] +
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'– such as:"123456789012312313134124512351145145114"4)'urn'Such 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 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 is used 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=)
  • Serialization field option parameter
The parameter name role
max_length The maximum length
min_lenght Minimum length
allow_blank Whether to allow null
trim_whitespace Whether to truncate whitespace characters
max_value The minimum value
min_value The maximum
  • Serialization field generic parameter
The parameter name instructions
read_only The default value is False. If the value is set to True, this field can be seen in Postman and does not need to be transmitted when data is modified
write_only The default value is False. If the value is set to True, this field is not displayed in Postman
required Indicates that this field must be entered when deserializing, and defaults to True
default Default value to use when deserializing
allow_null Indicates whether the field is allowed to pass 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 display when HTML displays the API page
help_text Field help information displayed when HTML displays the API page

conclusion

The article was first published in the wechat public account Program Yuan Xiaozhuang, at the same time in nuggets.

The code word is not easy, reprint please explain the source, pass by the little friends of the lovely little finger point like and then go (╹▽╹)