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)