• rest_framework 序列化


    1.common

    serializer.py

    #/usr/bin/env python3
    # -*- coding:utf-8 -*-
    #   mail: infaaf@126.com
    
    from app01.models import UserGroup,UserInfo,Role
    from rest_framework import  serializers
    from app01 import models
    
    class UserInfoSerializer(serializers.Serializer):
        ut=serializers.CharField(source='get_user_type_display')
        username=serializers.CharField()
        password=serializers.CharField()
        group=serializers.CharField(source='group.title')
        rls=serializers.SerializerMethodField()   # 或models中定制方法source参数引用
    
        def get_rls(self,row):
            role_obj_list=row.roles.all()
            ret=[]
            for item in role_obj_list:
                ret.append({'id':item.id,'tile':item.title})
            return ret
    
    class UserInfoSerializer2(serializers.ModelSerializer):
        ut = serializers.CharField(source='get_user_type_display')
        group=serializers.CharField(source='group.title')
        rls=serializers.SerializerMethodField()
    
        def get_rls(self,row):
            role_obj_list=row.roles.all()
            ret=[]
            for item in role_obj_list:
                ret.append({'id':item.id,'tile':item.title})
            return ret
    
        class Meta:
            model=models.UserInfo
            # fields='__all__'
            fields=['id','username','password','ut','group','rls']
    
    
    class UserInfoSerializer3(serializers.ModelSerializer):
        class Meta:
            model=models.UserInfo
            # fields='__all__'
            fields='__all__'
            depth = 1    #  Foreignkey和manytomany 自动获取详细。 choice仍需手动处理
    
    
    class XXX:
        def __init__(self,base):
            self.base=base
    
        def __call__(self, value):
            if not value.startwith(self.base):
                message='false'
                raise serializers.ValidationError(message)
    
    
    class UserInfoSerializerXXX(serializers.Serializer):
        # 校验字段
        name=serializers.CharField(error_messages={'required':'标题不能为空'})
        
        # 利用validators
        XX=serializers.CharField(validators=[XXX('basename')])
    
        # 利用hook
        xx2=serializers.CharField()
        def validate_xx2(self,value):
            if value:
                return value
    
            # from rest_framework import exceptions
            # raise exceptions.ValidationError('xxx')
    View Code

    views.py

    from django.shortcuts import render,HttpResponse
    
    # Create your views here.
    from app01.models import UserGroup,UserInfo,Role
    from rest_framework.views import APIView
    
    from rest_framework.versioning import  QueryParameterVersioning,URLPathVersioning
    from django.urls import reverse
    from rest_framework.parsers import JSONParser,FormParser
    from app01.serializer import UserInfoSerializer,UserInfoSerializer2,UserInfoSerializer3,UserInfoSerializerXXX
    import json
    
    class D(APIView):
    
        versioning_class = URLPathVersioning
        parser_classes=[JSONParser,FormParser]   # print(request.data)
        def get(self,request,*args,**kwargs):
            print(kwargs.get('version'))
            print("##")
            print(request.version)
            print(request.versioning_scheme.reverse(viewname='userapi',request=request))
            r=reverse(viewname='userapi',kwargs={'version':'v1'})
            print(r)
            print(request.body)
            return HttpResponse('ok')
    
        def post(self,request,*args,**kwargs):
            # self.dispatch()
            print(request._request)
            pass
    
    
    
    class SerView(APIView):
        def get(self, request, *args, **kwargs):
            userinfo_obj=UserInfo.objects.all()
            ser=UserInfoSerializer3(instance=userinfo_obj,many=True)
            ret=json.dumps(ser.data,ensure_ascii=False)
            return HttpResponse(ret)
    
        def post(self, request, *args, **kwargs):
            ser=UserInfoSerializerXXX(data=request.data)
            if ser.is_valid():
                print(ser.validated_data)
            else:
                print(ser.errors)
            return HttpResponse('wrong')
    View Code

    models.py

    #/usr/bin/env python3
    # -*- coding:utf-8 -*-
    #   mail: infaaf@126.com
    from django.db import models
    from rest_framework import request
    
    class UserGroup(models.Model):
        title=models.CharField(max_length=32)
    
        def __str__(self):
            return self.title
    
    
    class UserInfo(models.Model):
        user_type_choice=((1,'普通用户'),
                          (2,'vip'),
                          (3,'SVIP'))
        user_type = models.IntegerField(choices=user_type_choice)
        username=models.CharField(max_length=32)
        password=models.CharField(max_length=64)
        group=models.ForeignKey('UserGroup',on_delete=None)
        roles=models.ManyToManyField('Role')
    
        def __str__(self):
            return self.username
    
    class UserToken(models.Model):
        user=models.OneToOneField(UserInfo,on_delete=None)
        token=models.CharField(max_length=64)
    
        def __str__(self):
            return self.token
    
    
    class Role(models.Model):
        title=models.CharField(max_length=32)
    
        def __str__(self):
            return self.title
    View Code

    2. extra

    hylinkedModelSerializer 使用url替代id。 这里额外定制了field信息

    class ProfileSerializer(serializers.HyperlinkedModelSerializer):
    
        url = serializers.HyperlinkedIdentityField(
                view_name='profile-detail',
                lookup_field='id'
            )
    
        owner = serializers.HyperlinkedIdentityField(
                view_name='user-detail',
                lookup_field='id'
            )
    
        class Meta:
            model = Profile
            fields = ( 'url', 'city', 'owner')
    View Code
  • 相关阅读:
    CentOS/RHEL 查看用户登陆信息
    PAM
    块存储
    ECS
    SQL 基础应用
    MySQL 基础管理
    MySQL 体系结构
    JSON对象
    设置dom节点属性的代码优化
    Ext框架下的元素拖动
  • 原文地址:https://www.cnblogs.com/infaaf/p/9573175.html
Copyright © 2020-2023  润新知