• django restframework 序列化


    Serialization 序列化

    创建表

    from django.db import models
    from pygments.lexers import get_all_lexers
    from pygments.styles import get_all_styles
    
    LEXERS = [item for item in get_all_lexers() if item[1]]
    LANGUAGE_CHOICES = sorted([(item[1][0], item[0]) for item in LEXERS])
    STYLE_CHOICES = sorted((item, item) for item in get_all_styles())
    
    
    class Snippet(models.Model):
        created = models.DateTimeField(auto_now_add=True)
        title = models.CharField(max_length=100, blank=True, default='')
        code = models.TextField()
        linenos = models.BooleanField(default=False)
        language = models.CharField(choices=LANGUAGE_CHOICES, default='python', max_length=100)
        style = models.CharField(choices=STYLE_CHOICES, default='friendly', max_length=100)
    
        class Meta:
            ordering = ('created',)
    

    进行序列化的类(第一种)

    from rest_framework import serializers
    from snippets.models import Snippet, LANGUAGE_CHOICES, STYLE_CHOICES
    
    
    class SnippetSerializer(serializers.Serializer):
        id = serializers.IntegerField(read_only=True)
        title = serializers.CharField(required=False, allow_blank=True, max_length=100)
        code = serializers.CharField(style={'base_template': 'textarea.html'})
        linenos = serializers.BooleanField(required=False)
        language = serializers.ChoiceField(choices=LANGUAGE_CHOICES, default='python')
        style = serializers.ChoiceField(choices=STYLE_CHOICES, default='friendly')
        """上面的相当于form表单验证 缺点: 如果表的列比较多呢"""
    
        def create(self, validated_data):
            """
            Create and return a new `Snippet` instance, given the validated data.
            """
            return Snippet.objects.create(**validated_data)
    
        def update(self, instance, validated_data):
            """
            Update and return an existing `Snippet` instance, given the validated data.
            """
            instance.title = validated_data.get('title', instance.title)
            instance.code = validated_data.get('code', instance.code)
            instance.linenos = validated_data.get('linenos', instance.linenos)
            instance.language = validated_data.get('language', instance.language)
            instance.style = validated_data.get('style', instance.style)
            instance.save()
            return instance            
    

    序列化类常用的方法和属性

    snippet = Snippet(code='foo = "bar"
    ')
    serializer = SnippetSerializer(snippet)
    serializer.data  # .data存储model的数据
    # {'id': 2, 'title': u'', 'code': u'print "hello, world"
    ', 'linenos': False, 'language': u'python', 'style': u'friendly'}
    #序列化转成json数据#
    content = JSONRenderer().render(serializer.data)
    content
    # '{"id": 2, "title": "", "code": "print \"hello, world\"\n", "linenos": false, "language": "python", "style": "friendly"}'
    
    #反序列化#
    
    from django.utils.six import BytesIO
    
    stream = BytesIO(content)
    data = JSONParser().parse(stream)
    
    serializer = SnippetSerializer(data=data)
    serializer.is_valid()
    # True
    serializer.validated_data
    # OrderedDict([('title', ''), ('code', 'print "hello, world"
    '), ('linenos', False), ('language', 'python'), ('style', 'friendly')])
    serializer.save()
    # <Snippet: Snippet object>
    
    serializer = SnippetSerializer(Snippet.objects.all(), many=True)
    serializer.data
    # [OrderedDict([('id', 1), ('title', u''), ('code', u'foo = "bar"
    '), ('linenos', False), ('language', 'python'), ('style', ...
    

    序列化的类(第二种)简单明了

    class SnippetSerializer(serializers.ModelSerializer):
    class Meta:
        model = Snippet 表名
        fields = ('id', 'title', 'code', 'linenos', 'language', 'style')  列
    

    view文件

    get(获取): 
        snippets = Snippet.objects.all() #从model取出所有数据
        serializer = SnippetSerializer(snippets, many=True)  # 进行序列化
        return JsonResponse(serializer.data, safe=False) # 返回客户端
        
    post(创建新的数据):
        data = JSONParser().parse(request) # 反序列化客户端数据
        serializer = SnippetSerializer(data=data)  # 实例化
        if serializer.is_valid():   # 检查数据是否有问题
            serializer.save() # 创建数据
            return JsonResponse(serializer.data, status=201) # 返回给客户端刚刚创建的数据
        return JsonResponse(serializer.errors, status=400)
        
    put(更新数据):
        data = JSONParser().parse(request)
        serializer = SnippetSerializer(snippet, data=data)
        if serializer.is_valid():
            serializer.save()
            return JsonResponse(serializer.data)
        return JsonResponse(serializer.errors, status=400)
    
    delete(删除数据):
        snippet.delete()
        return HttpResponse(status=204)
  • 相关阅读:
    判断是否是三角形,三角形面积,三角形内外切圆半径和面积
    输入从a加到b的两个数字
    九九乘法表
    某公司销售员工的年终奖根据该员工的年销售总额s提成,年销售总额超过1万元才提成,超过部分提成比例如下:
    判断是否是闰年?
    从键盘上输入三个点的坐标值(1,1)、(2,4)、(3,2),编程求该三角形的面积。
    输入一个正方形的边长,输出正方形的外接圆和内接圆的面积。
    .输入一个4位正整数,以相反的次序输出,例如,输入1234,输出为4321。
    SecoClient在win10系统中连接失败解决方案
    PHP 关于判断输入日期是否合法
  • 原文地址:https://www.cnblogs.com/wspblog/p/8178854.html
Copyright © 2020-2023  润新知