Django REST framework框架

序列化器

功能:进行数据的序列化和反序列化.

序列化功能:将对象转换为字典。
反序列化功能:数据校验-----数据保存-新增和更新

  • 安装DRF框架
pip install djangorestframework
  • 添加rest_framework应用, 将rest_framework在INSTALLED_APPS中进行注册
INSTALLED_APPS = [
    ...
    'rest_framework',
]

序列化器类定义

使用中更多使用serializers.ModelSerializer

from rest_framework import serializers

class <序列化器类>(serializers.Serializer):
	# 字段 = serializers.字段类型(选项参数)


举例:

class Goods(object):
	def __init__(self, name, price):
		self.name = btitle
		self.price = price
    
# 问题:
# 1. 定义序列化器类GoodsSerializer,将goods对象进行序列化:{"name": "苹果", "price": 20.0}
class GoodsSerializer(serializers.Serializer):
  name = serializers.CharField()
  price = serializers.DecimalField()

# 2. 如果传递了req_data = {"name": "桃子", "price": 10.5},反序列化校验能否通过?

if __name__ == "__main__":
  	req_data = {"name": "桃子", "price": 10.5}
    # 创建序列化器对象
    serializer = GoodsSerializer(data=req_data)
    # 校验:参数完整性,数据类型
    serializer.is_valid()
    # 错误提示
    serializer.errors
    # 校验之后的数据
    serializer.validated_data
    
if __name__ == "__main__":
  	# 创建Goods实例对象
    goods = Goods('苹果', 20.0)
    
    # 创建序列化器对象
    serializer = GoodsSerializer(goods)
    serializer.data

选项参数

2. 新增一本图书数据
API: POST /books/
参数:
	json
	{
		"btitle": "书名",
		"bpub_date": "出版日期"
	}
响应:	
	status=201
	json
	{
		"id": "图书id",
		"btitle": "书名",
		"bpub_date": "出版日期",
		"bread": "阅读量",
		"bcomment": "评论量"
	}
	
class BookInfoSerializer(serializers.Serializer):
	id = serializers.IntegerField(read_only=True)
	btitle = serializers.CharField()
  bpub_date = serializers.DateTimeField()

  bread = serializers.IntegerField(read_only=True)
  bcomment = serializers.InterField(read_only=True)
  
  
req_data = {"btitle": "图书", "bpub_date": "2010-01-01"}
serializer = BookInfoSerializer(data=req_data)
serializer.is_valid()

2. 新增一本图书数据
API: POST /books/
参数:
	json
	{
		"btitle": "书名", # 必传
		"bpub_date": "出版日期", # 必传
		"bread": "阅读量", # 可以不传
		"bcomment": "评论量" # 可以不传
	}
响应:	
	status=201
	json
	{
		"id": "图书id",
		"btitle": "书名",
		"bpub_date": "出版日期",
		"bread": "阅读量",
		"bcomment": "评论量"
	}
	
class BookInfoSerializer(serializers.Serializer):
	id = serializers.IntegerField(read_only=True)
	btitle = serializers.CharField()
  bpub_date = serializers.DateTimeField()
  bread = serializers.IntegerField(required=False)
  bcomment = serializers.InterField(required=False)

4)default:设置反序列化和序列化时使用的默认值

posted @ 2019-08-01 22:33  太虚真人  阅读(215)  评论(0编辑  收藏  举报