rest_framework-序列化-总结完结篇

Posted liang-jc

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了rest_framework-序列化-总结完结篇相关的知识,希望对你有一定的参考价值。

#rest_framework 序列化
from rest_framework import serializers

#serilizers.Serializer serializers.ModelSerializer 两种序列化方式

class RolesSerializer(serializers.Serializer):
    id = serializers.IntegerField()
    title = serializers.CharField()

class RolesView(APIView):
    def get(self, request, *args, **kwargs):
        #方式1
        #roles = models.Role.objects.all().values(id,title)
        #roles = list(roles)
        #ret = json.dumps(roles, ensure_ascii=False)

        #方式2-1
        roles = models.Role.objects.all()
        ser = RolesSerializer(instance=roles, many=True)
        ret = json.dumps(ser.data, ensure_ascii=False)
        return HttpResponse(ret)

        #方式2-2
        roles = models.Role.objects.all().first()
        ser = RolesSerializer(instance=roles, many=False)
        ret = json.dumps(ser.data, ensure_ascii=False)
        return HttpResponse(ret)

class UserInfoSerializer(serializers.Serializer):
    username = serializer.CharField()
    password = serializer.CharField()
    user_type = serializer.IntegerField()

    #user_type = serializer.Charield(source="get_user_type_display")  #找到每一行的对象 row.user_type
                                                          # row.get_user_type_display  就可以对choices进行层级的字符
                                                          #可执行

    gp = serializers.CharField(source="group.title")  #外键group关联Group表,通过.获取Group表字段参数
    #显示 [{"username":"ljc", "password":"123", "user_type":"VIP", "gp":"A组"}]

    #多对多 manytomany 不能通过source  通过serializers.SerializerMethodField()
    roles = serializers.SerializerMethodField() #自定义显示
    def get_roles(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):
        users = models.UserInfo.objects.all()
        ser = UserInfoSerializer(instance=users, many=True)
        ret = json.dumps(ser.data, ensure_ascii=False)

        return HttpResponse(ret)

#方式3
class UserInfoSerializer(serializers.ModelSerializer):
    user_type = serializer.Charield(source="get_user_type_display")  #混合使用

    roles = serializers.SerializerMethodField() #自定义显示
    class Meta:
        model = models.UserInfo
        #fields = "__all__"  全部自动生成
        #fields = [id, username, password] #自定义
        #fields = [id, username, password, user_type]
        fields = [roles] #复杂的

        def get_roles(self, row):

            role_obj_list = row.roles.all() #获取角色对象
            ret = []
            for item in role_obj_list:
                ret.append({id:item.id, title:item.title})



class UserInfoView(APIView):
    def get(self, request, *args, **kwargs):
        users = models.UserInfo.objects.all()
        ser = UserInfoSerializer(instance=users, many=True)
        ret = json.dumps(ser.data, ensure_ascii=False)

        return HttpResponse(ret)

#小清新版
class UserInfoSerializer(serializers.ModelSerializer):
    class Meta:
        model = models.UesrInfo
        fields = "__all__"
        depth = 1  #这个就可以将所有的数据都显示了  默认为0 只是关联本表的数据 depth最好0-4层就好了
                   #表与表之间的manytomany onetoone foreignkey 表示一层 第二个表再关联 就2层  连表操作
class UserInfoView(APIView):
    def get(self, request, *args, **kwargs):

        users = models.UserInfo.objects.all()
        ser = UserInfoSerializer(instance=users, many=True)

        ret - json.dumps(ser.data, ensure_ascii=False) #ensure_ascii=False 显示中文
        return HttpResponse(ret)

 

以上是关于rest_framework-序列化-总结完结篇的主要内容,如果未能解决你的问题,请参考以下文章

rest_framework-版本-总结完结篇

rest_framework-权限-总结完结篇

rest_framework-节流-总结完结篇

python Django Rest_Framework框架 反序列化时数据校验的三种方法(图文并茂版)

Django.rest_framework:如何序列化一对多?

如何使 rest_framework 序列化器禁止多余的字段?