基本用法

视图里通过查询数据库 queryset 例如: Article.objects.all()
queryset 里的 字段需要跟 序列化字段对象一一对应,才能通过序列化对象序列化对象

  1. from datetime import datetime
  2. from rest_framework import serializers
  3. from rest_framework.renderers import JSONRenderer
  4. from django.utils.six import BytesIO
  5. from rest_framework.parsers import JSONParser
  6. class Comment(object):
  7. def __init__(self, email, content, created=None):
  8. self.email = email
  9. self.content = content
  10. self.created = created or datetime.now()
  11. comment = Comment(email='leila@example.com', content='foo bar')
  12. class CommentSerializer(serializers.Serializer):
  13. email = serializers.EmailField()
  14. content = serializers.CharField(max_length=200)
  15. created = serializers.DateTimeField()
  16. # 序列化
  17. serializer = CommentSerializer(comment)
  18. json = JSONRenderer().render(serializer.data)
  19. # 反序列化
  20. stream = BytesIO(json)
  21. data = JSONParser().parse(stream)

新增实例,如何判断哪些字段必传

author = serializers.CharField(required=True) 需要传值
author = serializers.CharField(required=False) 不需要传值

变更字段名,添加source

author_name = serializers.CharField(required=True, source=’author’)

嵌套对象

将一个序列化对象作为 field 存入另一个序列化对象