python test development django-rest-framework-64. serialization (serializers.Serializer)

Foreword

The serializers in the REST framework are very similar to Django’s Form and ModelForm classes. We provide a Serializer class that provides you with powerful general methods to control the output of the response,
and a ModelSerializer class that provides a useful shortcut for creating serializers for working with model instances and querysets.

serializers.Serializer

Let’s start with a simple case. Edit models.py in the apiapp directory. Take creating a user personal information model as an example.

# models.py
from django.db import models
# Author: Shanghai Youyou, QQ communication group: 750815713


# Create your models here.
class UserPersonalInfo(models.Model):
    '''User personal information'''
    name = models.CharField(max_length=10, verbose_name="nickname") # Nickname
    sex_choices = (
        (u'M', u'male'),
        (u'F', u'female'),
    )
    sex = models.CharField(max_length=11,
                           choices=sex_choices,
                           verbose_name="gender",
                            )
    age = models.IntegerField(verbose_name="age", default="", blank=True)
    mail = models.EmailField(max_length=30, default="", blank=True)
    create_time = models.DateField(auto_now=True, verbose_name="Add time")

Execute makemigrations and migrate to synchronize the database

python manage.py makemigrations
python manage.py migrate

Serializer is the simplest serialization base class in rest_framework and has the lowest encapsulation. But this base class is more flexible, and we can use this class to customize the serialization class we need.
Implementing this class requires overriding two methods, create and update.

  • The create method corresponds to what we access through POST when using the API, because the data we need to create a new instance is usually passed through POST.
  • The update method corresponds to accessing the API through the PUT/PATCH method, which is used to create a new instance or update an existing instance, depending on whether the instance we need to operate exists in the database.

Create a new serializersapi.py file in the apiapp directory. In this file, first edit the model that needs to be serialized. The id is a field that comes with the system by default.

│ manage.py
├─apiapp
│ │ admin.py
│ │ apps.py
│ │ auth.py
│ │ models.py
│ │ serializersapi.py
│ │ tests.py
│ │ views.py
│ │ __init__.py
│ │
│ ├─migrations
│ │ │ 0001_initial.py
│ │ │ 0002_userpersonalinfo.py
│ │ │ __init__.py
│
└─yoyoapi
    │ settings.py
    │ urls.py
    │wsgi.py
    │ __init__.py

When writing a serialization class, the relevant parameters verbose_name and blank in the field must be removed.

# serializersapi.py
from rest_framework import serializers
from .models import UserPersonalInfo

class UserPersonalInfoSerializer(serializers.Serializer):
    id = serializers.IntegerField(read_only=True)
    name = serializers.CharField(max_length=10) # Nickname
    sex_choices = (
        (u'M', u'male'),
        (u'F', u'female'),
    )
    sex = serializers.ChoiceField(choices=sex_choices
                            )
    age = serializers.IntegerField(default="")
    mail = serializers.EmailField(max_length=30, default="")
    create_time = serializers.DateField(read_only=True)


    def create(self,validated_data):
        return UserPersonalInfo.objects.create(**validated_data)


    def update(self,instance,validated_data):
        instance.name = validated_data.get('name', instance.name)
        instance.sex = validated_data.get('sex', instance.sex)
        instance.age = validated_data.get('age', instance.age)
        instance.mail = validated_data.get('mail', instance.mail)
        instance.save()
        return instance

When creating ArticleSerializer, some fields are created, which represent the fields corresponding to the model when the Serializer class is serialized. These fields should have the same names as the fields defined in the model.

When defining, some parameters were specified. Only read_only is used here, and there are other parameters.

  • write_only,required,allow_null/allow_blank,label,help_text,style,error_messages
  • read_only: Indicates that this field can only be used for API output, and users cannot directly specify the value of this field.
  • write_only: This is the opposite of read_only, which requires the user to specify the value of the field.
  • required: This field is required and cannot be empty
  • allow_null/allow_blank: This field is allowed to be null/empty
  • label: label, used to set field display settings
  • help_text: a piece of text explaining the field, used for prompts
  • style: describes the type of field
  • error_messages: Information prompts when field errors occur

The instancece parameter in the update method is a model instance or a custom class instance. In fact, the model is just a class, which just encapsulates some ORM operations at the bottom layer.

views.py view

# views.py
from rest_framework.response import Response
from rest_framework.views import APIView
from .models import *
from rest_framework.permissions import IsAuthenticated,AllowAny
from .serializersapi import UserPersonalInfoSerializer
# Author: Shanghai Youyou, QQ communication group: 750815713


class UserPersonalInfoView(APIView):
    '''REST framework's APIView implementation obtains the UserPersonalInfo table # Author: Shanghai Youyou, QQ communication group: 750815713'''
    # authentication_classes = (TokenAuthentication,) # token authentication
    # permission_classes = (IsAuthenticated,) # IsAuthenticated Only authenticated users
    permission_classes = (AllowAny,) # Allow all users

    def get(self, request, format=None):
        """
        Return a list of all UserPersonalInfo
        """
        info = UserPersonalInfo.objects.all()
        serializer = UserPersonalInfoSerializer(info, many=True)
        return Response(serializer.data)

    def post(self, request, format=None):
        '''
        createUserPersonalInfo
        '''
        verify_data = UserPersonalInfoSerializer(data=request.data)
        if verify_data.is_valid():
            verify_data.save()
            return Response({"message": "create some data!", "data": request.data})
        else:
            return Response(verify_data.errors)

urls.py sets access path

# urls.py
from apiapp import views
from django.conf.urls import url


# Author: Shanghai Youyou, QQ communication group: 750815713


urlpatterns = [
    url(r'^userinfo', views.UserPersonalInfoView.as_view()),
]

Test interface

Visit ‘http://127.0.0.1:8000/userinfo’, post request test results

POST http://127.0.0.1:8000/userinfo HTTP/1.1
User-Agent: Fiddler
Host: 127.0.0.1:8000
Content-Length: 82
Content-Type: application/json

{
"name": "yoyo",
"sex": "M",
"age": "20",
"mail": "[email protected]"
}

The new addition is successful. Check the database and a piece of data will be generated.

Visit ‘http://127.0.0.1:8000/userinfo’ to get the request test results