Python test development django-rest-framework-65. Serialization (ModelSerializer)

Foreword

serializers.Serializer can serialize fields in the model model, and two methods, create and update, must be written. ModelSerializer can be regarded as an upgraded version of Serializer, which is more powerful and convenient.
In fact, the ModelSerializer class inherits the Serializer class.

ModelSerializer

The ModelSerializer class allows you to automatically create a Serializer class with the corresponding fields in the model. This ModelSerializer class is the same as the regular Serializer class, except that:

  • It automatically generates a set of fields based on the model.
  • It automatically generates validators for serializers, such as the unique_together validator.
  • It simply implements the .create() method and the .update() method by default.

For example, a model we created models.py

# 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")

Use ModelSerializer to serialize as follows

# serializersapi.py
from rest_framework import serializers
from .models import UserPersonalInfo
# Author: Shanghai Youyou, QQ communication group: 750815713


class UserInfoSerializer(serializers.ModelSerializer):
    class Meta:
        model = UserPersonalInfo
        fields = '__all__'

Setting the fields parameter to '__all__' will serialize all fields by default and can be viewed in the django shell interactive mode

D:\soft\yoyoapi>python manage.py shell
Python 3.6.0 (v3.6.0:41df79263a11, Dec 23 2016, 08:06:12) [MSC v.1900 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
>>> from apiapp.serializersapi import UserInfoSerializer
>>> serializer = UserInfoSerializer()
>>> print(repr(serializer))
UserInfoSerializer():
    id = IntegerField(label='ID', read_only=True)
    name = CharField(label='nickname', max_length=10)
    sex = ChoiceField(choices=(('M', 'Male'), ('F', 'Female')), label='Gender')
    age = IntegerField(label='age', max_value=2147483647, min_value=-2147483648, required=False)
    mail = EmailField(allow_blank=True, max_length=30, required=False)
    create_time = DateField(label='Add time', read_only=True)
>>>

fields specifies the fields to be included

If I only want a few of the fields, such as ‘id’, ‘name’, ‘mail’, ‘create_time’, then the fields parameter can be set to a tuple type

# serializersapi.py
from rest_framework import serializers
from .models import UserPersonalInfo
# Author: Shanghai Youyou, QQ communication group: 750815713


class UserInfoSerializer(serializers.ModelSerializer):
    class Meta:
        model = UserPersonalInfo
        fields = ('id', 'name', 'mail', 'create_time')

After modifying the code, you need to exit() to exit the shell and then re-enter. Run django shell in interactive mode to view the results

D:\soft\yoyoapi>python manage.py shell
Python 3.6.0 (v3.6.0:41df79263a11, Dec 23 2016, 08:06:12) [MSC v.1900 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
>>> from apiapp.serializersapi import UserInfoSerializer
>>> serializer = UserInfoSerializer()
>>> print(repr(serializer))
UserInfoSerializer():
    id = IntegerField(label='ID', read_only=True)
    name = CharField(label='nickname', max_length=10)
    mail = EmailField(allow_blank=True, max_length=30, required=False)
    create_time = DateField(label='Add time', read_only=True)
>>>

exclude excluded field list

Contrary to the fields attribute setting, you can use exclude to exclude some fields

# serializersapi.py
from rest_framework import serializers
from .models import UserPersonalInfo
# Author: Shanghai Youyou, QQ communication group: 750815713


class UserInfoSerializer(serializers.ModelSerializer):
    class Meta:
        model = UserPersonalInfo
        # fields = ('id', 'name', 'mail', 'create_time')
        exclude = ('id', 'sex', 'age')

View results in django shell interactive mode

# Author: Shanghai Youyou, QQ communication group: 750815713
D:\soft\yoyoapi>python manage.py shell
Python 3.6.0 (v3.6.0:41df79263a11, Dec 23 2016, 08:06:12) [MSC v.1900 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
>>> from apiapp.serializersapi import UserInfoSerializer
>>> serializer = UserInfoSerializer()
>>> print(repr(serializer))
UserInfoSerializer():
    name = CharField(label='nickname', max_length=10)
    mail = EmailField(allow_blank=True, max_length=30, required=False)
    create_time = DateField(label='Add time', read_only=True)
>>>

In the above example, using the exclude parameter will exclude the three parameters ‘id’, ‘sex’, and ‘age’.

Case Operation

Next, use serializers.ModelSerializer to serialize (set fields = ‘all‘), write a simple case, edit the views.py view, and change this sentence based on the previous article. Can

verify_data = UserInfoSerializer(data=request.data) # Only change this

# 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 UserInfoSerializer

class UserInfoView(APIView):
    '''APIView implementation of REST framework to obtain card list # 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 = UserInfoSerializer(info, many=True)
        return Response(serializer.data)

    def post(self, request, format=None):
        '''
        createUserPersonalInfo
        '''
        verify_data = UserInfoSerializer(data=request.data) # Only change this
        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 the access address

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


# Author: Shanghai Youyou, QQ communication group: 750815713


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

Test interface

GET request to access http://127.0.0.1:8000/info and query the results

POST request submitted http://127.0.0.1:8000/info, test results