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

A list,

The serialization component in Djangos REST Framework is the core component of the framework and the most commonly used component. It provides not only serialization functionality, but also data validation functionality (similar to forms in Django).

For easy serialization, we need to add a foreign key, many-to-many case to the model. Here is the new models(delete the original database and migrate again) :

models.py

from django.db import models

class UserInfo(models.Model) :
    user_type_choice = (
        (1."Ordinary user"),
        (2."Membership"),
    )
    user_type = models.IntegerField(choices=user_type_choice)
    username = models.CharField(max_length=32,unique=True)
    password = models.CharField(max_length=64)
    group = models.ForeignKey(to='UserGroup',null=True,blank=True)
    roles = models.ManyToManyField(to='Role')


class UserToken(models.Model) :
    user = models.OneToOneField(to=UserInfo)
    token = models.CharField(max_length=64)



class UserGroup(models.Model) :
    """ User Group ""
    name = models.CharField(max_length=32,unique=True)


class Role(models.Model) :
    "" "role "" "
    name = models.CharField(max_length=32,unique=True)
Copy the code

Second, the use of

1. Basic use

Add a new character URL to urls.py. The previous URL is commented here to reduce interference:

from django.conf.urls import url
from app01 import views

urlpatterns = [

    # url(r'^api/v1/auth', views.AuthView.as_view()),# url(r'^api/v1/order', views.OrderView.as_view()),
    url(r'^api/v1/roles', views.RoleView.as_view()),  # role view
    # url(r'^api/(? P
      
       [v1|v2]+)/user', views.UserView.as_view(),name="user_view"),
      
]
Copy the code

views.py

from rest_framework import serializers
from rest_framework.views import APIView
from django.shortcuts import  HttpResponse
from  app01 import  models
import json


class RolesSerializer(serializers.Serializer) : # define serialized classes
    id=serializers.IntegerField()  # Define the serialized fields to extract with the same names as those defined in model
    name=serializers.CharField()
class RoleView(APIView) :
    "" "role "" "
    def get(self,request,*args,**kwargs) :
        roles=models.Role.objects.all()
        res=RolesSerializer(instance=roles,many=True) #instance accepts either a QuerySet object or a single Model object. Dumps (res.data, ensure_ASCII =False) use many=True, single object many=Falsereturn HttpResponse(json.dumps(res.data, ensure_ASCII =False))
Copy the code

Access using a browserhttp://127.0.0.1:8000/api/v1/roles, the results are as follows:

2. Customize the serialization field

Custom serialization is required when there are foreign keys or many-to-many in the data model

Added the URL of user information

from django.conf.urls import url
from app01 import views

urlpatterns = [

    # url(r'^api/v1/auth', views.AuthView.as_view()),# url(r'^api/v1/order', views.OrderView.as_view()),
    url(r'^api/v1/roles', views.RoleView.as_view()),
    url(r'^api/v1/userinfo', views.UserinfoView.as_view()), # User information
    # url(r'^api/(? P
      
       [v1|v2]+)/user', views.UserView.as_view(),name="user_view"),
      
]
Copy the code

UserinfoView and serialization class

class UserinfoSerializer(serializers.ModelSerializer) :
    id = serializers.IntegerField()  # Define the serialized fields to extract with the same names as those defined in model
    username=serializers.CharField()
    password=serializers.CharField()
    # SSS =serializers.CharField(source='user_type'
    sss=serializers.CharField(source='get_user_type_display') Get_user_type_display () = get_user_type_display()
    #rl=serializers.CharField(source='roles.all.first.name')
    gp=serializers.CharField(source='group.name')
    rl=serializers.SerializerMethodField()   Many-to-many serialization method 1
    def get_rl(self,obj) : Get_ defines the field name
        """ Custom serialization: Param obj: The model object passed, encapsulated here :return: """
        roles=obj.roles.all().values() Get all the characters

        return list(roles)  The return result must be a JSON serializable object
    class Meta:
        model = models.UserInfo
        fields = ['id'.'username'.'password'.'sss'.'rl'.'gp'] Configure the fields to serialize
        # fields = "__all__" use all fields in model

class UserinfoView(APIView) :
    "" user Information ""
    def get(self,request,*args,**kwargs) :
        users=models.UserInfo.objects.all()
        res=UserinfoSerializer(instance=users,many=True) # Instance accepts either a QuerySet object or a single model object, using many=True when there are multiple pieces of data and many=False for a single object
        return HttpResponse(json.dumps(res.data,ensure_ascii=False))
Copy the code

Visit http://127.0.0.1:8000/api/v1/userinfo to view the results:

In addition to the Serializer above, you can also use ModelSerializer, which inherits from Serializer and has the same result as the example above:

class UserinfoSerializer(serializers.ModelSerializer) :
    id = serializers.IntegerField()  # Define the serialized fields to extract with the same names as those defined in model
    username=serializers.CharField()
    password=serializers.CharField()
    # SSS =serializers.CharField(source='user_type'
    sss=serializers.CharField(source='get_user_type_display') Get_user_type_display () = get_user_type_display()
    #rl=serializers.CharField(source='roles.all.first.name')
    gp=serializers.CharField(source='group.name')
    rl=serializers.SerializerMethodField()   Many-to-many serialization method 1
    def get_rl(self,obj) : Get_ defines the field name
        """ Custom serialization: Param obj: The model object passed, encapsulated here :return: """
        roles=obj.roles.all().values() Get all the characters

        return list(roles)  The return result must be a JSON serializable object
    class Meta:
        model = models.UserInfo
        fields = ['id'.'username'.'password'.'sss'.'rl'.'gp'] Configure the fields to serialize
        # fields = "__all__" use all fields in model

class UserinfoView(APIView) :
    "" user Information ""
    def get(self,request,*args,**kwargs) :
        users=models.UserInfo.objects.all()
        res=UserinfoSerializer(instance=users,many=True) # Instance accepts either a QuerySet object or a single model object, using many=True when there are multiple pieces of data and many=False for a single object
        return HttpResponse(json.dumps(res.data,ensure_ascii=False))
Copy the code

3. Serial table serialization and depth control

Depth is used for depth control. The deeper the serialized peruse, the higher the serialized peruse

class UserinfoSerializer(serializers.ModelSerializer) :

    class Meta:
        model = models.UserInfo
        #fields = "__all__" # use all fields in model
        fields = ['id'.'username'.'password'.'group'.'roles']  Configure the fields to serialize
        depth = 1  # Serialization depth, 1~10, recommended to use less than 3
class UserinfoView(APIView) :
    "" user Information ""
    def get(self,request,*args,**kwargs) :
        users=models.UserInfo.objects.all()
        res=UserinfoSerializer(instance=users,many=True) # Instance accepts either a QuerySet object or a single model object, using many=True when there are multiple pieces of data and many=False for a single object
        return HttpResponse(json.dumps(res.data,ensure_ascii=False))
Copy the code

Request to http://127.0.0.1:8000/api/v1/userinfo, the results are as follows:

4. Serialize the field URL

Urls.py new group URL

urlpatterns = [

    # url(r'^api/v1/auth', views.AuthView.as_view()),# url(r'^api/v1/order', views.OrderView.as_view()),
    url(r'^api/v1/roles', views.RoleView.as_view()),
    url(r'^api/v1/userinfo', views.UserinfoView.as_view()),
    url(r'^api/v1/group/(? P
      
       \d+)'
      , views.GroupView.as_view(),name='gp'),  Add new group URL
    # url(r'^api/(? P
      
       [v1|v2]+)/user', views.UserView.as_view(),name="user_view"),
      Copy the code

views.py

class UserinfoSerializer(serializers.ModelSerializer) :
    group=serializers.HyperlinkedIdentityField(view_name='gp',lookup_field='group_id',lookup_url_kwarg='xxx')
    #view_name, urls.py View alias (name) of the target URL, in this case the view alias of UserGroup
    #lookup_field The parameter passed to the URL, that is, the field that the re matches
    #lookup_url_kwarg, the name of the regular in the URL, which is the key in kwargs
    class Meta:
        model = models.UserInfo
        #fields = "__all__" # use all fields in model
        fields = ['id'.'username'.'password'.'roles'.'group']  Configure the fields to serialize
        depth = 1  # Serialization depth, 1~10, recommended to use less than 3
class UserinfoView(APIView) :
    "" user Information ""
    def get(self,request,*args,**kwargs) :
        users=models.UserInfo.objects.all()
        res=UserinfoSerializer(instance=users,many=True,context={'request': request}) # Instance accepts either a QuerySet object or a single model object, using many=True when there are multiple pieces of data and many=False for a single object
        Context ={'request': request} context={'request': request}
        return HttpResponse(json.dumps(res.data,ensure_ascii=False))

class UserGroupSerializer(serializers.ModelSerializer) :
    class Meta:
        model = models.UserGroup
        fields = "__all__"
        depth = 0


class GroupView(APIView) :
    def get(self,request,*args,**kwargs) :

        group_id=kwargs.get('xxx')
        group_obj=models.UserGroup.objects.get(id=group_id)
        res=UserGroupSerializer(instance=group_obj,many=False) # Instance accepts either a QuerySet object or a single model object, using many=True when there are multiple pieces of data and many=False for a single object
        return HttpResponse(json.dumps(res.data,ensure_ascii=False))
Copy the code

At this time access group information: http://127.0.0.1:8000/api/v1/group/1, the results are as follows:

When viewing user information, the generated group is in the form of hyperlinks (for viewing JSON data, postman is used to send requests) :