码迷,mamicode.com
首页 > 其他好文 > 详细

[Django rest-framework] 1-Serialization

时间:2017-08-01 16:40:40      阅读:282      评论:0      收藏:0      [点我收藏+]

标签:logs   lex   read_only   创建   div   stream   接下来   使用   instance   

个人粗浅的理解,欢迎批评指正

什么是序列化?

  后端任务无非对数据库的增查删改,操作数据库无非操作字段,序列化可以让我们轻松的对数据库增(serializer.create)改(serilaizer.update)的同时不用担心提交的key/value是否合法(serializer.is_valid),并轻松的将dict 格式转为更通用的json格式(JSONRenderer)

什么是反序列化?

  将json转为JSONParser().parse(stream)可序列化的dict(serializer(data=data))

跟着教程走一波

先安装一下virtualenv

新建一个虚拟环境env

进入env虚拟环境

sudo apt-get install virtualenv
virtualenv env
source env/bin/activate

 

 离开虚拟环境:deactivate

ps:如果使用pycharm IDE,在file-settings-Project:XXX-Project Interpreter,将项目解释器设置为虚拟环境中安装的python

在我们的虚拟环境中安装其他所需库

pip install django
pip install djangorestframework
pip install pygments # 用来高亮代码的库

 创建项目,创建app

cd ~
django-admin.py startproject tutorial
cd tutorial

 

python manage.py startapp snippets

 记得settings.INSTALLED_APPS中添加刚才创建的app

INSTALLED_APPS = (
    ...
    ‘rest_framework‘,
    ‘snippets.apps.SnippetsConfig‘,
)

 django 创建一个django模型

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‘,)

 有没有菜鸡跟我一样才发现,原来从模型这里就可以限制字段的可选值(choices)

Meta元类中的ordering是指quarySet排序按’created‘字段来

django的orm

操作下数据库

python manage.py makemigrations snippets
python manage.py migrate

 重点到了,新建一个serializers.py 文件,并创建我们的序列化类

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‘)

    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

 create和update是必须在子类中实现的方法,因为调用serializer.save()方法会用到他们

serializer类和django的model类很相似,可以在声明的时候限制字段的属性

接下来看看怎么使用序列化类

先打开django shell

python manage.py shell

 然后创建两个数据

from snippets.models import Snippet
from snippets.serializers import SnippetSerializer
from rest_framework.renderers import JSONRenderer
from rest_framework.parsers import JSONParser

snippet = Snippet(code=‘foo = "bar"\n‘)
snippet.save()

snippet = Snippet(code=‘print "hello, world"\n‘)
snippet.save()

接着:

1:序列化

serializer = SnippetSerializer(snippet)
serializer.data
# {‘id‘: 2, ‘title‘: u‘‘, ‘code‘: u‘print "hello, world"\n‘, ‘linenos‘: False, ‘language‘: u‘python‘, ‘style‘: u‘friendly‘}

 2:转json

content = JSONRenderer().render(serializer.data)
content
# ‘{"id": 2, "title": "", "code": "print \\"hello, world\\"\\n", "linenos": false, "language": "python", "style": "friendly"}‘

 3:转dict

from django.utils.six import BytesIO

stream = BytesIO(content)
data = JSONParser().parse(stream)

 4:反序列化

serializer = SnippetSerializer(data=data)
serializer.is_valid()
# True
serializer.validated_data
# OrderedDict([(‘title‘, ‘‘), (‘code‘, ‘print "hello, world"\n‘), (‘linenos‘, False), (‘language‘, ‘python‘), (‘style‘, ‘friendly‘)])
serializer.save()
# <Snippet: Snippet object>

 5:支持序列化多个数据

serializer = SnippetSerializer(Snippet.objects.all(), many=True)
serializer.data
# [OrderedDict([(‘id‘, 1), (‘title‘, u‘‘), (‘code‘, u‘foo = "bar"\n‘), (‘linenos‘, False), (‘language‘, ‘python‘), (‘style‘, ‘friendly‘)]), OrderedDict([(‘id‘, 2), (‘title‘, u‘‘), (‘code‘, u‘print "hello, world"\n‘), (‘linenos‘, False), (‘language‘, ‘python‘), (‘style‘, ‘friendly‘)]), OrderedDict([(‘id‘, 3), (‘title‘, u‘‘), (‘code‘, u‘print "hello, world"‘), (‘linenos‘, False), (‘language‘, ‘python‘), (‘style‘, ‘friendly‘)])]

 

看到这里感觉序列化就是将form对象转为dict格式,将quaryset转为OrderedDict

下节学习一下,正真更通用的ModelSerializers

 参考资料:http://www.django-rest-framework.org/tutorial/1-serialization/#tutorial-1-serialization

[Django rest-framework] 1-Serialization

标签:logs   lex   read_only   创建   div   stream   接下来   使用   instance   

原文地址:http://www.cnblogs.com/lazySmeagol/p/7251634.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!