Serializer 容許複雜數據(好比 querysets 和 model 實例)轉換成python數據類型,而後能夠更容易的轉換成 json 或 xml 等。同時,Serializer也提供了反序列化功能,容許解析數據轉換成複雜數據類型。python
咱們來建立一個簡單對象做爲例子:json
from datetime import datetime class Comment(object): def __init__(self, email, content, created=None): self.email = email self.content = content self.created = created or datetime.now() comment = Comment(email='leila@example.com', content='foo bar')
而後咱們聲明一個serializer ui
from rest_framework import serializers class CommentSerializer(serializers.Serializer): email = serializers.EmailField() content = serializers.CharField(max_length=200) created = serializers.DateTimeField()
serializer = CommentSerializer(comment) serializer.data # {'email': 'leila@example.com', 'content': 'foo bar', 'created': '2016-01-27T15:17:10.375877'}
這時咱們已經轉換model 實例成了python 數據類型,接下來咱們將它轉換成json 格式spa
from rest_framework.renderers import JSONRenderer json = JSONRenderer().render(serializer.data) json # b'{"email":"leila@example.com","content":"foo bar","created":"2016-01-27T15:17:10.375877"}'
反序列化就是將json或xml等格式轉換成複雜數據類型rest
serializer = CommentSerializer(data=data) serializer.is_valid() # True serializer.validated_data # {'content': 'foo bar', 'email': 'leila@example.com', 'created': datetime.datetime(2012, 08, 22, 16, 20, 09, 822243)}
反序列化數據的時候,在訪問有效數據或保存對象實例以前,你應該老是調用 is_valid() ,以查看是否反序列化成功,若是有錯誤, .errors 屬性包含錯誤信息。code
serializer = CommentSerializer(data={'email': 'foobar', 'content': 'baz'}) serializer.is_valid() # False serializer.errors # {'email': [u'Enter a valid e-mail address.'], 'created': [u'This field is required.']}
若是你但願返回基於驗證數據(validated data,也就是反序列化後的數據)的完整的對象實例,你須要實現.create() 或 .update() 方法。xml
class CommentSerializer(serializers.Serializer): email = serializers.EmailField() content = serializers.CharField(max_length=200) created = serializers.DateTimeField() def create(self, validated_data): return Comment(**validated_data) def update(self, instance, validated_data): instance.email = validated_data.get('email', instance.email) instance.content = validated_data.get('content', instance.content) instance.created = validated_data.get('created', instance.created) return instance
如今,當你反序列化數據時,你須要調用.save() 方法返回對象實例,基於驗證的數據(validated data)對象
comment = serializer.save()
調用save() 時,要麼建立一個新實例,要麼更新一個已存在的實例,這取決於你是否傳入了實例參數blog
# .save() will create a new instance. serializer = CommentSerializer(data=data) # .save() will update the existing `comment` instance. serializer = CommentSerializer(comment, data=data)