• Django rest-framework框架-序列化


    序列化:
    
    第一版:
    class RolesView(APIView):
          def get(self,request,*args,**kwargs):
              roles = models.Role.objects.all().values('id','title')
              roles = list(roles)
              #利用json.dumps将数据转换成json格式
              ret = json.dumps(roles,ensure_ascii=False)
              return HttpResponse(ret)
    
    第二版:
    from rest_framework import serializers
    
    class RloesSerializer(serializers.Serializer):
          id = serializers.IntegerField()
          title = serializers.CharField()
    
    class RolesView(APIView):
          def get(self,request,*args,**kwargs):
              方式一:对于[obj,obj,obj,]  
              roles = models.Role.objects.all()
              ser = RloesSerializer(instance=roles, many=True) #多个对象 
    
              方式二:对于[obj,obj,obj,]
              roles = models.Role.objects.all().first() 
              ser = RloesSerializer(instance=roles, many=False) #单个对象或数据
    
              ret = json.dumps(ser.data,ensure_ascii=False)
              return HttpResponse(ret)
    
    第三版:
    from rest_framework import serializers
    
    class UserInfoSerializer(serializers.Serializer):
          # source是印射models里面的表的字段名
          user_type = serializers.CharField(source='user_type')
          # 如果字段时choices字段 可以使用source='get_字段名_display' 来显示中文
          user_type_zhongwen = serializers.CharField(source='get_user_type_display')
          username = serializers.CharField()
          password = serializers.CharField()
          #如果字段是一个Forenighkey那么可以使用 字段名加点来关联其他表的字段
          gpid = serializers.CharField(source='group.id')
          #如果字段是一个ManyToMany那么可以使用 字段名加点来关联所有字段
          rls = serializers.CharField(source='roles.all')
          #自定义显示
          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,'title':item.title})
              return ret
    
    class UserInfoView(APIView):
          def get(self,request,*args,**kwargs): 
              roles = models.UserInfo.objects.all()
              ser = UserInfoSerializer(instance=roles, many=True) #多个对象 
     
              ret = json.dumps(ser.data,ensure_ascii=False)
              return HttpResponse(ret)
    

      

    第四版:
    from rest_framework import serializers
    
    class UserInfoSerializer(serializers.ModelSerializer):
    #反向生成url 根据路由 url(r^(?P<version>[v1|v2]+)/group/(?P<pk>d+)$, view.UserInfoView.as_view(),'gp')
    group = serializers.HyperlinkedIdentityField(view_name='gp',lookup_field='group_id',lookup_url_kwarg='pk') user_type_zhongwen = serializers.CharField(source='get_user_type_display') class Meta: model = models.UserInfo # 显示UserInfo全部字段 fields = "__all__" # 可以自定义字段 fields = ['id','username','password','user_type_zhongwen',]
              #默认是0,大于等于1时 就会把字段的相关的Forengishkey或者ManyToMany或者OneToOne
    #建议不要超过3 (0-10) depth = 1 class UserInfoView(APIView): def get(self,request,*args,**kwargs): roles = models.UserInfo.objects.all() ser = UserInfoSerializer(instance=roles, many=True) #多个对象 ret = json.dumps(ser.data,ensure_ascii=False) return HttpResponse(ret)

      

    使用第四版

    1. 继承 serializers.ModelSerializer 

    2. class Meta:

                 model = models.<表名>

                 fields = "__all__"

    3. 可以自定义字段  fields = ['id','username','password','user_type_zhongwen',]

    4. depth = 1  #默认是0,大于等于1时 就会把字段的相关的Forengishkey或者ManyToMany或者OneToOne

  • 相关阅读:
    pipeline流水线语法格式
    nexus私服配置npm、nuget、pypi
    正则表达式-grep
    awk 经典案例
    nginx安装,配置,及高可用
    git remote add origin错误
    [转]Git 撤销操作
    [转]git命令之git remote的用法
    [转]git学习------>git-rev-parse命令初识
    转 gerrit
  • 原文地址:https://www.cnblogs.com/kuku0223/p/11347634.html
Copyright © 2020-2023  润新知