基本用法
视图里通过查询数据库 queryset 例如: Article.objects.all()
queryset 里的 字段需要跟 序列化字段对象一一对应,才能通过序列化对象序列化对象
from datetime import datetime
from rest_framework import serializers
from rest_framework.renderers import JSONRenderer
from django.utils.six import BytesIO
from rest_framework.parsers import JSONParser
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')
class CommentSerializer(serializers.Serializer):
email = serializers.EmailField()
content = serializers.CharField(max_length=200)
created = serializers.DateTimeField()
# 序列化
serializer = CommentSerializer(comment)
json = JSONRenderer().render(serializer.data)
# 反序列化
stream = BytesIO(json)
data = JSONParser().parse(stream)
新增实例,如何判断哪些字段必传
author = serializers.CharField(required=True) 需要传值
author = serializers.CharField(required=False) 不需要传值
变更字段名,添加source
author_name = serializers.CharField(required=True, source=’author’)
嵌套对象
将一个序列化对象作为 field 存入另一个序列化对象