DRF: serializer

Keywords: Django

A Serializer serializer

effect:

serialize,The serializer converts the model object into a dictionary,after response Later become json character string
 Deserialization,Send the data sent by the client,after request Later become a dictionary,Serializers can turn dictionaries into models
 Deserialization,Complete data verification function

1.1 defining serializers

Serializer in Django REST framework is defined by class and must inherit from rest_framework.serializers.Serializer.

First, we need to have the database model class Publish:

from django.db import models

# Create your models here.
class Publish(models.Model):
    nid = models.AutoField(primary_key=True,verbose_name='number')
    name = models.CharField(max_length=32,verbose_name='name')
    city = models.CharField(max_length=32,verbose_name='City')
    email = models.EmailField(verbose_name='mailbox')

    def __str__(self):
        return self.name

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

Define the PublishSerializer class that inherits the serializer class in serializer.py.

from rest_framework import serializers


class PublishSerializer(serializers.Serializer):
    nid = serializers.IntegerField(required=False)
    name = serializers.CharField(max_length=32,error_messages={
        'max_length':'It's too long, boy'
    })
    city = serializers.CharField()
    email = serializers.EmailField()

  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.

Common field types:

fieldField construction method
BooleanFieldBooleanField()
NullBooleanFieldNullBooleanField()
CharFieldCharField(max_length=None, min_length=None, allow_blank=False, trim_whitespace=True)
EmailFieldEmailField(max_length=None, min_length=None, allow_blank=False)
RegexFieldRegexField(regex, max_length=None, min_length=None, allow_blank=False)
SlugFieldSlugField(maxlength=50, min_length=None, allow_blank=False) regular field, verify the regular pattern [a-zA-Z0-9 -]+
URLFieldURLField(max_length=200, min_length=None, allow_blank=False)
UUIDFieldUUIDField(format=’hex_verbose’) format: 1)  ' hex_ verbose'   Such 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"
IPAddressFieldIPAddressField(protocol='both', unpack_ipv4=False, **options)
IntegerFieldIntegerField(max_value=None, min_value=None)
FloatFieldFloatField(max_value=None, min_value=None)
DecimalFieldDecimalField(max_digits, decimal_places, coerce_to_string=None, max_value=None, min_value=None) max_digits: maximum digits decimal_palces: decimal point position
DateTimeFieldDateTimeField(format=api_settings.DATETIME_FORMAT, input_formats=None)
DateFieldDateField(format=api_settings.DATE_FORMAT, input_formats=None)
TimeFieldTimeField(format=api_settings.TIME_FORMAT, input_formats=None)
DurationFieldDurationField()
ChoiceFieldChoiceField(choices) choices are used in the same way as Django
MultipleChoiceFieldMultipleChoiceField(choices)
FileFieldFileField(max_length=None, allow_empty_file=False, use_url=UPLOADED_FILES_USE_URL)
ImageFieldImageField(max_length=None, allow_empty_file=False, use_url=UPLOADED_FILES_USE_URL)
ListFieldListField(child=, min_length=None, max_length=None)
DictFieldDictField(child=)

Option parameters:

Parameter nameeffect
max_lengthMaximum length
min_lenghtMinimum length
allow_blankAllow null
trim_whitespaceTruncate white space characters
max_valueminimum value
min_valueMaximum

General parameters:

Parameter nameexplain
read_onlyIndicates that this field is only used for serialized output. The default is False
write_onlyIndicates that this field is only used for deserialization input. The default is False
requiredIndicates that this field must be entered during deserialization. The default is True
defaultDefault value to use when deserializing
allow_nullIndicates whether the field is allowed to pass in None. The default is False
validatorsValidator used by this field
error_messagesA dictionary containing error numbers and error messages
labelThe name of the field to be displayed when displaying API pages in HTML
help_textIt is used to display field help prompt information when HTML displays API pages

1.2 creating Serializer objects

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

The construction method of PublishSerializer is:

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

explain:

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 the instance and data parameters, when constructing the PublishSerializer object, you can also add additional data through the context parameter, such as

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

The data attached through the context parameter can be obtained through the context attribute of the PublishSerializer 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.
  3. The field declaration of the serializer is similar to the form system we used earlier.
  4. When developing restful api, serializer will help us convert model data into 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

1.3 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.

1.3.1 serialization

1.3.1.1 basic use

1) Query a publishing house object first

from app01 import models

publish = models.Publish.objects.filter(pk=id).first()

2) Construct serializer object

from app01 import serializer

publish_ser = serializer.PublishSerializer(instance=publish)

3) Get serialized data

The serialized data can be obtained through the data attribute

serializer.data
# {'id': 4, 'name': 'Xiao Zhang', 'age': 18, 'sex': True, 'description': 'monkey Sai Lei'}

Full view code:

from rest_framework.views import APIView
from rest_framework.response import Response
from app01 import models
# Create your views here.
from app01 import serializer

class PublishDetailView(APIView):
    """Serialize and transform individual model data using serializer"""
    def get(self,request,id):
        # get data
        publish = models.Publish.objects.filter(pk=id).first()
        # Data conversion [serialization process]
        publish_ser = serializer.PublishSerializer(instance=publish)
        print(publish_ser.instance)
        # Response data
        return Response(publish_ser.data)

4) If the query set to be serialized is a QuerySet containing multiple pieces of data, you can add the many=True parameter to supplement the description


class PublishView(APIView):
"""Serialize and transform multiple model data using serializer"""
    def get(self,request):
        # get data
        publish_qs = models.Publish.objects.all()
        # Response data to client
        # If the returned json data is a list, you need to declare safe=False
        publish_ser = serializer.PublishSerializer(instance=publish_qs,many=True)
        return Response(publish_ser.data,safe=False)

Write the interface instance about the addition, deletion, modification and query of the publishing house through Serializer serialization.

Step 1: build the database model class Publish in models.py, and use the make migrations and migrate commands

from django.db import models

# Create your models here.
class Publish(models.Model):
    nid = models.AutoField(primary_key=True,verbose_name='number')
    name = models.CharField(max_length=32,verbose_name='name')
    city = models.CharField(max_length=32,verbose_name='City')
    email = models.EmailField(verbose_name='mailbox')

    def __str__(self):
        return self.name

Step 2: create a serialization class PublishSerializer in serializer.py and inherit Serializer

class PublishSerializer(serializers.Serializer):
    nid = serializers.IntegerField(required=False)
    name = serializers.CharField(max_length=32,error_messages={
        'max_length':'It's too long, boy'
    })
    city = serializers.CharField()
    email = serializers.EmailField()

Step 3: create the view class PublishView class and PublishDetailView class that inherit APIView in views.py

from rest_framework.views import APIView
from rest_framework.response import Response
from app01 import models
# Create your views here.
from app01 import serializer


class PublishView(APIView):
    # get requests all publisher information
    def get(self,request):      
        publish_qs = models.Publish.objects.all()
        # Serialize all information. Here, many is set to True
        publish_ser = serializer.PublishSerializer(instance=publish_qs,many=True)
        return Response(publish_ser.data)
    # post requests to add a piece of publisher data
    def post(self,request):
        publish_ser = serializer.PublishSerializer(data=request.data)
        if publish_ser.is_valid():
            publish_ser.save()
            return Response(publish_ser.data)
        else:
            print(publish_ser.errors)
            return Response(publish_ser.errors)


class PublishDetailView(APIView):
    # get request a single piece of publisher information
    def get(self,request,id):    
        publish = models.Publish.objects.filter(pk=id).first()
        publish_ser = serializer.PublishSerializer(instance=publish)
        print(publish_ser.instance)
        return Response(publish_ser.data)

    # put requests to modify a piece of publisher information
    def put(self,request,id):
        print(request.data)
        publish = models.Publish.objects.filter(pk=id).first()
        publish_ser = serializer.PublishSerializer(instance=publish,data=request.data)
        if publish_ser.is_valid():
            publish_ser.save()
            return Response(publish_ser.data)
        else:
            return Response('Data verification error')

    # Delete requests to delete a piece of publisher information
    def delete(self,request,id):
        res = models.Publish.objects.filter(pk=id).first()
        print(res)
        if res[0]>0:
            return Response('')
        else:
            return Response('The to delete does not exist')


Step 4: when using post request and put request, the data in the database has changed, so we need to save the serialized data. Therefore, in the PublishSerializer class of serialzier.py, we need to override the create() and update() methods:

    def create(self, validated_data):
        res = models.Publish.objects.create(**validated_data)
        return res

    def update(self, instance, validated_data):

        name = validated_data.get('name')
        city = validated_data.get('city')
        email = validated_data.get('email')
        instance.name = name
        instance.city = city
        instance.email = email

        instance.save()
        return instance

Step 5: add routes for PublishView class and PublishDetailView class in urls.py. Remember to register rest in apps in settings.py_ Framework application.

from django.contrib import admin
from django.urls import path
from app01 import views
urlpatterns = [
    path('admin/', admin.site.urls),
    path('publish/',views.PublishView.as_view()),
    path('publish/<int:id>',views.PublishDetailView.as_view())
]

Step 6: start the django project and enter the interface address and operation data in postman.

Posted by menwn on Tue, 23 Nov 2021 16:15:03 -0800