On what serialization and deserialization are (4)

【 turn https://blog.csdn.net/YangHeng816/article/details/78534186 POST request -- -- -- -- -- -- -- -- - > the deserialization process -- -- -- -- -- -- -- > deserializer: Json → Native datatype【data = JSONParser().parse(BytesIO(content))】 → isntance【serializer = SnippetSerializer(data=data)  serializer.is_valid()# True serializer. The save () 】GET request -- -- -- -- -- -- -- -- -- -- > the serialization process -- -- -- -- -- -- -- -- -- -- > serilization: Isntance (Django model instance) → native datatype (Python native datatype) 【serializer. Data 】 → Json【JSONRenderer().render(serializer. Data)】, Convert the response of the Model instance to JSON. From the design principles of REST, it is actually to meet the needs of the client, now the Web back end and the client (ios/ Android) deal with a lot, such a formatted response is easier for them to parse. In other words: something that packages the response in some format, such as JSON. 】Copy the code

Official Documentation

SerializerMethodField this is a read-only field.

It gets its value by calling the methods of the serializer class to which it is attached and can be used to add any type of data to the serialized representation of an object

Signature: SerializerMethodField(method_name=None)

Method_name – The name of the method on the serializer to be called.

If this default is not included, get_<field_name>.

The serializer method referenced by the method_name parameter should take an argument (except self) that is the object being serialized.

It should return whatever you want to include in the serialized representation of the object

Now let’s try it

Complete example code

models.py
from django.db import models

# Create your models here.
from django.contrib.auth.models import AbstractBaseUser


class MyUsers(models.Model):
    #REQUIRED_FIELDS = ('name',)
    #USERNAME_FIELD = ('name')
    groups = models.ForeignKey(
        'Groups',
        null=False,
        blank=False,
        related_name='myusers',
        on_delete=models.CASCADE
    )
    name = models.CharField(
            null=False,
            blank=False,
            max_length=125,
    )
    email = models.EmailField(
            null=False,
            blank=False,
            max_length=125,
    )

    url = models.URLField(
            null=False,
            blank=True,
            max_length=125,
    )


class Groups(models.Model):
    name = models.CharField(
            null=False,
            blank=False,
            max_length=125,
    )

    url = models.URLField(
            null=False,
            blank=True,
            max_length=125,
    )

class Ip(models.Model):
    user = models.ForeignKey(
        'MyUsers',
        null=False,
        blank=False,
        related_name='ips',
        on_delete=models.CASCADE
    )
    group = models.ForeignKey(
        'Groups',
        null=False,
        blank=True,
        related_name='ips',
        on_delete=models.CASCADE
    )
    ip_addr = models.GenericIPAddressField(
        blank=False,
        null=False,
    )

serializers.py
from django.contrib.auth.models import User, Group
from rest_framework import serializers
from accounts.models import Ip


class UserSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = User
        fields = ('url'.'username'.'email'.'groups'.'user')


class GroupSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = Group
        fields = ('url'.'name')


class IpSerializer(serializers.HyperlinkedModelSerializer):
    #SerializerMethodField () : Serialization and deserialization
    group = serializers.SerializerMethodField()
    user = serializers.SerializerMethodField()
    class Meta:
        model = Ip
        fields = ('user'.'ip_addr'.'group')

    def get_group(self, obj):Call the method of the connected serializer class
        print(obj)
        group = obj.group
        print(group)
        print(group.url)
        return{'url': group.url,
               'name': group.name,
              }

    def get_user(self, obj):Add any type of data to the serialized representation of the object
        print(obj)
        user = obj.user
        print(user)
        if user:
            print(1)
        return {
            'name': user.name + ' ' + 'hello'
        }
        
views.py
from django.shortcuts import render
# Create your views here.
from django.contrib.auth.models import User, Group
from rest_framework import viewsets
from accounts.serializers import UserSerializer, GroupSerializer, IpSerializer
from rest_framework.authtoken.models import Token
from rest_framework.response import Response
from knox.auth import TokenAuthentication
from knox.models import AuthToken
from rest_framework.permissions import IsAuthenticated, AllowAny
from accounts.models import Ip


class UserViewSet(viewsets.ModelViewSet):
    authentication_classes = (
        TokenAuthentication,
    )
    permission_classes = (AllowAny,)
    queryset = User.objects.all().order_by('-date_joined').prefetch_related('groups')
    serializer_class = UserSerializer

    def create(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        user = serializer.save()
        auth_token = AuthToken.objects.create(user)
        # print(auth_token)
        return Response(
            {
                "email": user.email,
                "token": auth_token,
                "id": user.id,
                #"key": auth_token.key,})""" serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) user = serializer.save()  self.token = AuthToken.objects.create(user) print(request.user) self.headers = self.client.credentials(HTTP_AUTHORIZATION='Token ' + self.token) # token is setted into the requested headers # token =  Token.objects.create(user=user) print(self.token.key) """


# class UserViewSet(viewsets.ModelViewSet):
# "" "
Allow the user to view or edit the API path.
# "" "
# queryset = User.objects.all().order_by('-date_joined')
# serializer_class = UserSerializer
# def Post(self, request, *args, **kwargs):
# serializer = self.get_serializer(data=request.data)
# serializer.is_valid(raise_exception=True)
# user = serializer.save()
# token = Token.objects.create(user=user)
# print(token.key)
# # auth_token = AuthToken.objects.create(user)
# # print(auth_token.key)
# return Response(
# {
# "name": user.username,
# "token": token,
# "id": user.id,
#}
#)
#

class GroupViewSet(viewsets.ModelViewSet):
    """API path that allows groups to view or edit. """
    queryset = Group.objects.all()
    serializer_class = GroupSerializer


class IpViewSet(viewsets.ModelViewSet):
    """API path that allows groups to view or edit. """All () serializer_class = IpSerializer Floral/ load/balance files. Floral/ load/balance files Floral/urls.py(note: url under project) from Django.conf. urls import url, include from rest_framework import routers from accounts import views router = routers.DefaultRouter() router.register(r'users', views.UserViewSet)
router.register(r'groups', views.GroupViewSet)
router.register(r'ips', views.IpViewSet)

Connect to our API using automatic URL routing.
In addition, we include login urls that support the browser browsing API.
urlpatterns = [
    url(r'api/auth/', include('knox.urls')),
    url(rA '^', include(router.urls)),
    # url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework'))
]



Copy the code

The important thing to explain is that serialization is implemented with SerializerMethodField and a group is a foreign key in an Ip table, The associated MyUser model sets the data to be returned using the get_group() method. User is a custom serialized field that sets the data to be returned using the get_user() method



class IpSerializer(serializers.HyperlinkedModelSerializer):
    #SerializerMethodField () : Serialization and deserialization
    group = serializers.SerializerMethodField()
    user = serializers.SerializerMethodField()
    class Meta:
        model = Ip
        fields = ('user'.'ip_addr'.'group')

    def get_group(self, obj):Call the method of the connected serializer class
        print(obj)
        group = obj.group
        print(group)
        print(group.url)
        return{'url': group.url,
               'name': group.name,
              }

    def get_user(self, obj):Add any type of data to the serialized representation of the object
        print(obj)
        user = obj.user
        print(user)
        if user:
            print(1)
        return {
            'name': user.name + ' ' + 'hello'
        }
Copy the code

After executing python manage. Py runserver then executes, visit http://127.0.0.1:8000/ips/, the results


Django version 2.0.5, using settings 'Floral.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CONTROL-C.
(0.002) SELECT "accounts_ip"."id"."accounts_ip"."user_id"."accounts_ip"."group_id"."accounts_ip"."ip_addr" FROM "accounts_ip"; Args =() Ip object (1) (0.001) SELECT"accounts_myusers"."id"."accounts_myusers"."groups_id"."accounts_myusers"."name"."accounts_myusers"."email"."accounts_myusers"."url" FROM "accounts_myusers" WHERE "accounts_myusers"."id"= 1; Args =(1,) MyUsers object (1) 1 Ip object (1) (0.001) SELECT"accounts_groups"."id"."accounts_groups"."name"."accounts_groups"."url" FROM "accounts_groups" WHERE "accounts_groups"."id" = 1; args=(1,)
Groups object (1)
http://www.baidu.com
[31/May/2018 07:51:52] "GET /ips/ HTTP/1.1"200, 105,Copy the code

The results of using the postman test: https://note.youdao.com/yws/res/32197/WEBRESOURCE349824a3428c554357e2b7a7c27f7792