首页 > 其他分享 >序列化

序列化

时间:2023-10-22 17:45:39浏览次数:30  
标签:serializers name models import 序列化 class ser

### Serializer
#models.py
from django.db import models

class Role(models.Model):
    title = models.CharField(verbose_name="标题", max_length=32)
    order = models.IntegerField(verbose_name="顺序")



#views.py
from django.db import models


class Role(models.Model):
    title = models.CharField(verbose_name="标题", max_length=32)
    order = models.IntegerField(verbose_name="顺序")
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import serializers
from api import models


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


class InfoView(APIView):
    def get(self, request):
        # 1.数据库获取多条数据
        # queryset = models.Role.objects.all()
        # ser = InfoSerializer(instance=queryset, many=True)

        # 2.数据库获取单条数据
        instance = models.Role.objects.all().first()
        ser = InfoSerializer(instance=instance, many=False)
        print(type(ser.data), ser.data)
        return Response(ser.data)
----------------------------------------------------------------------------------------------------------------
### ModelSerializer
#models.py

from django.db import models

class Role(models.Model):
    title = models.CharField(verbose_name="标题", max_length=32)
    order = models.IntegerField(verbose_name="顺序"

#views.py

from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import serializers
from api import models


class InfoSerializer(serializers.ModelSerializer):
    class Meta:
        model = models.Role
        # fields = "__all__"
        # fields = ['id', 'title', 'order']
        exclude = ["id"]


class InfoView(APIView):
    def get(self, request):
        # 1.数据库获取多条数据
        # queryset = models.Role.objects.all()
        # ser = InfoSerializer(instance=queryset, many=True)

        # 2.数据库获取单条数据
        instance = models.Role.objects.all().first()
        ser = InfoSerializer(instance=instance, many=False)

        print(type(ser.data), ser.data)
        return Response(ser.data)

#使用ModelModelSerializer是要比Serializer更简洁一些的。
----------------------------------------------------------------------------------------------------------------
###字段和参数
###在ModelModelSerializer和Serializer中都可以自定义字段,并传入一些相关参数。
#models.py

from django.db import models


class Role(models.Model):
    title = models.CharField(verbose_name="标题", max_length=32)
    order = models.IntegerField(verbose_name="顺序")


class UserInfo(models.Model):
    name = models.CharField(verbose_name="姓名", max_length=32)
    gender = models.SmallIntegerField(verbose_name="性别", choices=((1, "男"), (2, "女")))
    role = models.ForeignKey(verbose_name="角色", to="Role", on_delete=models.CASCADE)
    ctime = models.DateTimeField(verbose_name="创建时间", auto_now_add=True)

#views.py

from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import serializers
from api import models


class InfoSerializer(serializers.ModelSerializer):
    gender = serializers.CharField(source="get_gender_display")
    role = serializers.CharField(source="role.title")
    ctime = serializers.DateTimeField(format="%Y-%m-%d")
    other_name = serializers.CharField(source="name")
    mine = serializers.SerializerMethodField()

    class Meta:
        model = models.UserInfo
        fields = ['id', 'name', 'gender', "role", 'ctime', "other_name", "mine"]

    def get_mine(self, obj):
        return "x-x-{}".format(obj.name)


class InfoView(APIView):
    def get(self, request):
        queryset = models.UserInfo.objects.all()
        ser = InfoSerializer(instance=queryset, many=True)
        print(type(ser.data), ser.data)
        return Response(ser.data)

image
序列化类嵌套

主要是ORM类中对应ForeignKey 和 ManyToManyField的字段进行序列化。

基于SerializerMethodField自定义方法对关联表数据进行序列化
基于嵌套的序列化类实现
image

# models
from django.db import models

class Role(models.Model):
    title = models.CharField(verbose_name="标题", max_length=32)
    order = models.IntegerField(verbose_name="顺序")


class Tag(models.Model):
    caption = models.CharField(verbose_name="名称", max_length=32)


class UserInfo(models.Model):
    name = models.CharField(verbose_name="姓名", max_length=32)
    gender = models.SmallIntegerField(verbose_name="性别", choices=((1, "男"), (2, "女")))
    role = models.ForeignKey(verbose_name="角色", to="Role", on_delete=models.CASCADE)
    ctime = models.DateTimeField(verbose_name="创建时间", auto_now_add=True)

    tags = models.ManyToManyField(verbose_name="标签", to="Tag")
# views
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import serializers
from api import models


class RoleSerializer(serializers.ModelSerializer):
    class Meta:
        model = models.Role
        # fields = "__all__"
        fields = ["id", 'title']


class TagSerializer(serializers.ModelSerializer):
    class Meta:
        model = models.Tag
        fields = "__all__"


class InfoSerializer(serializers.ModelSerializer):
    role = RoleSerializer()
    tags = TagSerializer(many=True)

    class Meta:
        model = models.UserInfo
        fields = ['id', 'name', "role", "tags"]


class InfoView(APIView):
    def get(self, request):
        queryset = models.UserInfo.objects.all()
        ser = InfoSerializer(instance=queryset, many=True)
        print(type(ser.data), ser.data)
        return Response(ser.data)
		
### 序列化类继承
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import serializers
from api import models


class MySerializer(serializers.Serializer):
    more = serializers.SerializerMethodField()

    def get_more(self, obj):
        return "123"


class InfoSerializer(serializers.ModelSerializer, MySerializer):
    class Meta:
        model = models.UserInfo
        fields = ["id", "name", 'more']


class InfoView(APIView):
    def get(self, request):
        instance = models.UserInfo.objects.all().first()
        ser = InfoSerializer(instance=instance, many=False)

        print(type(ser.data), ser.data)
        return Response(ser.data)

标签:serializers,name,models,import,序列化,class,ser
From: https://www.cnblogs.com/bxj123/p/17780745.html

相关文章

  • json序列化数据超出最大值(maxJsonLength)
    https://www.cnblogs.com/ellafive/p/13704301.html 1、序列化:以下代码在对象过大时会报错:进行序列化或反序列化时出错。字符串的长度超过了为maxJsonLength属性设置的值。//jsonObj比较大的时候会报错varserializer=newJavaScriptSerializer();returnserializer.Ser......
  • 序列化错误
    org.springframework.data.redis.serializer.SerializationException:Cannotserialize;nestedexceptionisorg.springframework.core.serializer.support.SerializationFailedException:FailedtoserializeobjectusingDefaultSerializer;nestedexceptionisjava.......
  • 【Java】Vert.x Jackson 序列化后日期数据正常展示
    有段时间没有更新了,年尾嘛大家都懂的。其实最近有个想法,想将自己的vtx_fw框架给开源了。但开源之前还是有很多收尾的工作需要做的(总不能让各位笑话吧o(╥﹏╥)o),这不今天就发现了一个问题,立刻就归纳一下给各位分享。这个问题就是Vert.x框架中日期类型数据在Jackson序列化下的......
  • gson如何序列化子类
    需求目前有一个需求,不同对象有一些公共属性,分别也有一些不同的属性。对方传过来的json字符串中,把这些对象组成了一个数组返回过来的。这样该如何反序列化呢?举例定义Person类、Student类、Worker类;@Data@ToStringpublicclassPerson{//姓名privateStringname;......
  • 由Django-Session配置引发的反序列化安全问题
    漏洞成因漏洞成因位于目标配置文件settings.py下关于这两个配置项SESSION_ENGINE:在Django中,SESSION_ENGINE 是一个设置项,用于指定用于存储和处理会话(session)数据的引擎。SESSION_ENGINE 设置项允许您选择不同的后端引擎来存储会话数据,例如:数据库后端 (django.contrib.sessions.b......
  • php反序列化键值逃逸
    又遇到键值逃逸了。这里提前说一下我的理解吧,这次理解比上几次遇到字符串逃逸还要深刻一点。譬如这次我是先写逃逸payload,然后使用"}; 闭合第一个逃逸部分,然后在后续插入新的字符串,也就是更改可控值,再用一次 "};闭合后续字符串。 详细的看题目吧。来自:[0CTF2016]piapiap......
  • PyYaml反序列化
    PyYaml反序列化之前做题还是比赛的时候碰到过一次,不是很懂原理,最近整理成知识块出来。PyYaml使用方法!!标签用于描述yaml文件存储的数据转化为python对象的解析格式importyamlimportospoc1="!!python/object/apply:nt.system[calc.exe]"poc2='!!python/object/new......
  • Java序列化与反序列化
    ......
  • 又一个难题:Java 序列化和反序列化为什么要实现 Serializable 接口?
    作者:椰子Tyshawn来源:https://blog.csdn.net/litianxiang_kaola最近公司的在做服务化,需要把所有model包里的类都实现Serializable接口,同时还要显示指定serialVersionUID的值.听到这个需求,我脑海里就突然出现了好几个问题,比如说:序列化和反序列化是什么?实现序列化和......
  • Jackson--FastJson--XStream--代码执行&&反序列化
    Jackson--FastJson--XStream--代码执行&&反序列化Jackson代码执行(CVE-2020-8840)影响范围2.0.0<=FasterXMLjackson-databindVersion<=2.9.10.2不受影响版本FasterXMLjackson-databind=2.8.11.5FasterXMLjackson-databind=2.9.10.3漏洞利用POC:Stringjson......