Django REST framework sequence of the source code analysis component and the global + local Hook

Serialization two functions

  a. queryset types of serialized

  b. of the data requested by the user verifies

 

a. queryset types of serialized

for example:

Table Design

 1 from django.db import models
 2 
 3 
 4 class UserGroup(models.Model):
 5     title = models.CharField(max_length=32)
 6 
 7 
 8 class UserInfo(models.Model):
 9     user_type_choices = (
10         (1, '普通用户'),
11         (2, 'vip'),
12         (3, 'svip'),
13     )
14     user_type = models.IntegerField(choices=user_type_choices)
15     username = models.CharField(max_length=32, unique=True)
16     password = models.CharField(max_length=64)
17     group = models.ForeignKey('UserGroup', on_delete=models.CASCADE)
18     roles = models.ManyToManyField('Role')
19 
20 
21 class UserToken(models.Model):
22     user = models.OneToOneField(to='UserInfo', on_delete=models.CASCADE)
23     token = models.CharField(max_length=64)
24 
25 
26 class Role(models.Model):
27     title = models.CharField(max_length=32)

Total route:

1 from django.contrib import admin
2 from django.urls import path, re_path, include
3 
4 urlpatterns = [
5     path('admin/', admin.site.urls),
6     re_path('api/', include('api.urls')),
7 ]

 

distribution:

# ! / Usr / bin / Python the env 
# - * - Coding: UTF-. 8 - * - 

from django.urls Import path, re_path, the include
 from API Import views 

the urlpatterns = [ 

    # serialization 
    re_path ( ' (P <Version>? [V1 | V2] +) / Roles / $ ' , views.RolesView.as_view ()), 
    re_path ( ' (P <Version> [V1 | V2]? +) / UserInfo / $ ' , views.UserInfoView.as_view ( )),
     # serialization and generate url View details restful back links 
   re_path ( ' (P <Version> [v1 | v2]?? +) / Group / (P <PK> \ d +) $ ' , views.GroupView.as_view (), name = 'group'),
    # 验证
    re_path('(?P<version>[v1|v2]+)/usergroup/$', views.UserGroupView.as_view()),

]

 

On the field of view serializers.Serializer Version 1 Preliminary inheritance

 1 import json
 2 from django.shortcuts import render, HttpResponse
 3 from rest_framework import serializers
 4 from api import models
 5 
 6 
 7 class RolesSerializer(serializers.Serializer):
 8     id = serializers.IntegerField()
 9     title = serializers.CharField()
10 
11 
12 class RolesView(APIView):
13 
14     def get(self, request, *args, **kwargs):
15         # 方式1
16         # roles = models.Role.objects.all().values('id', 'title')
17         # roles = list(roles)
18         # ret = json.dumps(roles, ensure_ascii=False)
19         # 方式2
20         # roles = models.Role.objects.all()
21         # ser = RolesSerializer(instance=roles, many=True)
22         # ret = json.dumps(ser.data, ensure_ascii=False)
23 
24         role = models.Role.objects.all().first()
25         ser = RolesSerializer(instance=role, many=False)
26         ret = json.dumps(ser.data, ensure_ascii=False)
27         return HttpResponse(ret)

 

Advanced 2 inherited serializers.Serializer version of the sequence class field to proceed

. 1  class UserInfoSerializer (serializers.Serializer):
 2      # user_type serializers.IntegerField = () 
. 3      UUU = serializers.CharField (Source = ' user_type ' )
 . 4      # whether the internal User type get_user_type_display callable if a direct call can not return directly 
5      = serializers.CharField OOO (Source = ' get_user_type_display ' )
 . 6      username = serializers.CharField ()
 . 7      password = serializers.CharField ()
 . 8      # display group name 
. 9      GP = serializers.CharField (Source = 'group.title ' )
 10      # for all users in the group display 
. 11      # Roles = serializers.CharField (Source =' roles.all ') is not enough # 
12      # processing ManyToManyField field 
13 is      Role = serializers.SerializerMethodField ()
 14      
15      DEF get_role ( Self, Row):
 16          role_obj_list = row.roles.all ()
 . 17          RET = []
 18 is          for Item in role_obj_list:
 . 19              ret.append ({ ' ID ' : item.id, ' title ': item.title})
20         return ret

Inheritance serializers.ModelSerializer version 3 for the field to proceed

 1 class UserInfoSerializer(serializers.ModelSerializer):
 2     ooo = serializers.CharField(source='get_user_type_display')
 3     # Serializer(BaseSerializer, metaclass=SerializerMetaclass)
 4     # ModelSerializer(Serializer)
 5     role = serializers.SerializerMethodField()
 6 
 7     class Meta:
 8         model = models.UserInfo
 9         # fields = '__all__'
10         fields = ['id', 'username', 'password', 'ooo', 'role',  'group']
11 
12     def get_role(self, row):
13         role_obj_list = row.roles.all()
14         ret = []
15         for item in role_obj_list:
16             ret.append({'id': item.id, 'title': item.title})
17         return ret

Even automatically operating table depth

. 1  class UserInfoSerializer (serializers.ModelSerializer):
 2      # OOO = serializers.CharField (Source = 'get_user_type_display') 
. 3      # the Serializer (BaseSerializer, the metaclass that = SerializerMetaclass) 
. 4      # ModelSerializer (the Serializer) 
. 5  
. 6      class Meta -:
 . 7          Model = models.UserInfo
 . 8          Fields = ' __all__ is ' 
. 9          depth. 1 =   # official 0-10 feel up to two layers, and a multiple response slow data

 

Link field returns json data to the user

. 1  class UserInfoSerializer (serializers.ModelSerializer):
 2      # OOO = serializers.CharField (Source = 'get_user_type_display') 
. 3      # the Serializer (BaseSerializer, the metaclass that = SerializerMetaclass) 
. 4      # ModelSerializer (the Serializer) 
. 5      # generates url View User Groups specification details link restful must add context = { 'request': request } in the example of the time field 
. 6      Group = serializers.HyperlinkedIdentityField (view_name = ' Group ' , lookup_field = ' group_id ' , lookup_url_kwarg = ' PK ' )
 . 7  
. 8      class Meta -:
 . 9         = Model models.UserInfo
 10          Fields = ' __all__ is ' 
. 11          depth. 1 =   # official 0-10 feel most layer 2 touches the line 
12 is  
13 is  
14  class UserInfoView (APIView):
 15      DEF GET (Self, Request, args *, ** kwargs):
 16          "" " 
. 17          taking data sequence of
 18 is          : param Request:
 . 19          : param args:
 20 is          : param kwargs:
 21 is          : return:
 22 is          " "" 
23 is          Users = models.UserInfo.objects.all ()
 24         ser = UserInfoSerializer(instance=users, many=True, context={'request': request})
25         ret = json.dumps(ser.data, ensure_ascii=False)
26         return HttpResponse(ret)

 

Provide url link address in the page display

 1 class GroupSerializer(serializers.ModelSerializer):
 2     class Meta:
 3         model = models.UserGroup
 4         fields = '__all__'
 5 
 6 
 7 class GroupView(APIView):
 8     def get(self, request, *args, **kwargs):
 9         pk = kwargs.get('pk')
10         obj = models.UserGroup.objects.filter(pk=pk).first()
11         ser = GroupSerializer(instance=obj, many=False)
12         return HttpResponse(json.dumps(ser.data, ensure_ascii=False))

 

 

b. the user verification request data

Custom validation rules validators + hook

 1 class XValidator(object):
 2     def __init__(self, base):
 3         self.base = base
 4 
 5     def __call__(self, value):
 6         if not value.startswith(self.base):
 7             message = '必须以%s 开头' % self.base
 8             raise serializers.ValidationError(message)
 9 
10     def set_context(self, serializer_field):
11         """
12         This hook is called by the serializer instance,
13         The Call to being Validation Prior Made.
 14          "" " 
15          # call before performing verification, serializer_fields current field object 
16          Pass 
. 17  
18 is  
. 19  class UserGroupSerializer (serializers.Serializer):
 20 is      title = serializers.CharField (error_messages, = { ' required ' : ' not empty ' }, validators = [XValidator ( ' letter or underscore ' ),])
 21      # local hook
 22 is      
23 is      DEF validate_title (Self, value):
 24          from the ValidationError rest_framework.exceptions Import
 25          Print (value)
26 # raise ValidationError ( 'hate little big, you let through') 
27          return value
 28      # global hook
 29      
30      DEF the validate (Self, attrs):
 31 is          Print (attrs)
 32          return attrs
 33 is  
34 is  
35  class UserGroupView (APIView):
 36      DEF POST (Self, Request, * args, ** kwargs):
 37 [          Ser = UserGroupSerializer (Data = request.data)
 38 is          IF ser.is_valid ():
 39              Print (ser.validated_data [ 'title'])
 40          the else :
 41 is              Print (ser.errors)
 42 is  
43 is          returnThe HttpResponse ( ' submit data ' )

 Sequence Analysis of Source Code Analysis Hook +

 updating....

 

Guess you like

Origin www.cnblogs.com/Alexephor/p/11306201.html