标签:自动 数据转换 关于 datetime rom 自己 out 目录 取数
作用:
1. 序列化,序列化器会把模型对象转换成字典,经过response以后变成json字符串
2. 反序列化,把客户端发送过来的数据,经过request以后变成字典,序列化器可以把字典转成模型
3. 反序列化,完成数据校验功能
Django REST framework中的Serializer使用类来定义,须继承自rest_framework.serializers.Serializer。
接下来,为了方便演示序列化器的使用,我们先创建一个新的子应用sers
python manage.py startapp sers
我们已有了一个数据库模型类students/Student
from django.db import models
# Create your models here.
class Student(models.Model):
# 模型字段
name = models.CharField(max_length=100,verbose_name="姓名",help_text="提示文本:账号不能为空!")
sex = models.BooleanField(default=True,verbose_name="性别")
age = models.IntegerField(verbose_name="年龄")
class_null = models.CharField(max_length=5,verbose_name="班级编号")
description = models.TextField(verbose_name="个性签名")
class Meta:
db_table="tb_student"
verbose_name = "学生"
verbose_name_plural = verbose_name
我们想为这个模型类提供一个序列化器,可以定义如下:
from rest_framework import serializers
# 声明序列化器,所有的序列化器都要直接或者间接继承于 Serializer
# 其中,ModelSerializer是Serializer的子类,ModelSerializer在Serializer的基础上进行了代码简化
class StudentSerializer(serializers.Serializer):
"""学生信息序列化器"""
# 1. 需要进行数据转换的字段
id = serializers.IntegerField()
name = serializers.CharField()
age = serializers.IntegerField()
sex = serializers.BooleanField()
description = serializers.CharField()
# 2. 如果序列化器集成的是ModelSerializer,则需要声明调用的模型信息
# 3. 验证代码
# 4. 编写添加和更新模型的代码
注意:serializer不是只能为数据库模型类定义,也可以为非数据库模型类的数据定义。serializer是独立于数据库之外的存在。
常用字段类型:
字段 | 字段构造方式 |
---|---|
BooleanField | BooleanField() |
NullBooleanField | NullBooleanField() |
CharField | CharField(max_length=None, min_length=None, allow_blank=False, trim_whitespace=True) |
EmailField | EmailField(max_length=None, min_length=None, allow_blank=False) |
RegexField | RegexField(regex, max_length=None, min_length=None, allow_blank=False) |
SlugField | SlugField(maxlength=50, min_length=None, allow_blank=False) 正则字段,验证正则模式 [a-zA-Z0-9-]+ |
URLField | URLField(max_length=200, min_length=None, allow_blank=False) |
UUIDField | UUIDField(format=‘hex_verbose‘) format: 1) ‘hex_verbose‘ 如"5ce0e9a5-5ffa-654b-cee0-1238041fb31a" 2) ‘hex‘ 如 "5ce0e9a55ffa654bcee01238041fb31a" 3)‘int‘ - 如: "123456789012312313134124512351145145114" 4)‘urn‘ 如: "urn:uuid:5ce0e9a5-5ffa-654b-cee0-1238041fb31a" |
IPAddressField | IPAddressField(protocol=‘both‘, unpack_ipv4=False, **options) |
IntegerField | IntegerField(max_value=None, min_value=None) |
FloatField | FloatField(max_value=None, min_value=None) |
DecimalField | DecimalField(max_digits, decimal_places, coerce_to_string=None, max_value=None, min_value=None) max_digits: 最多位数 decimal_palces: 小数点位置 |
DateTimeField | DateTimeField(format=api_settings.DATETIME_FORMAT, input_formats=None) |
DateField | DateField(format=api_settings.DATE_FORMAT, input_formats=None) |
TimeField | TimeField(format=api_settings.TIME_FORMAT, input_formats=None) |
DurationField | DurationField() |
ChoiceField | ChoiceField(choices) choices与Django的用法相同 |
MultipleChoiceField | MultipleChoiceField(choices) |
FileField | FileField(max_length=None, allow_empty_file=False, use_url=UPLOADED_FILES_USE_URL) |
ImageField | ImageField(max_length=None, allow_empty_file=False, use_url=UPLOADED_FILES_USE_URL) |
ListField | ListField(child=, min_length=None, max_length=None) |
DictField | DictField(child=) |
选项参数:
参数名称 | 作用 |
---|---|
max_length | 最大长度 |
min_lenght | 最小长度 |
allow_blank | 是否允许为空 |
trim_whitespace | 是否截断空白字符 |
max_value | 最小值 |
min_value | 最大值 |
通用参数:
参数名称 | 说明 |
---|---|
read_only | 表明该字段仅用于序列化输出,默认False |
write_only | 表明该字段仅用于反序列化输入,默认False |
required | 表明该字段在反序列化时必须输入,默认True |
default | 反序列化时使用的默认值 |
allow_null | 表明该字段是否允许传入None,默认False |
validators | 该字段使用的验证器 |
error_messages | 包含错误编号与错误信息的字典 |
label | 用于HTML展示API页面时,显示的字段名称 |
help_text | 用于HTML展示API页面时,显示的字段帮助提示信息 |
定义好Serializer类后,就可以创建Serializer对象了。
Serializer的构造方法为:
Serializer(instance=None, data=empty, **kwarg)
说明:
1)用于序列化时,将模型类对象传入instance参数
2)用于反序列化时,将要被反序列化的数据传入data参数
3)除了instance和data参数外,在构造Serializer对象时,还可通过context参数额外添加数据,如
serializer = AccountSerializer(account, context={‘request‘: request})
通过context参数附加的数据,可以通过Serializer对象的context属性获取。
序列化器的使用分两个阶段:
1) 先查询出一个学生对象
from students.models import Student
student = Student.objects.get(id=3)
2) 构造序列化器对象
from .serializers import StudentSerializer
serializer = StudentSerializer(instance=student)
3)获取序列化数据
通过data属性可以获取序列化后的数据
serializer.data
# {‘id‘: 4, ‘name‘: ‘小张‘, ‘age‘: 18, ‘sex‘: True, ‘description‘: ‘猴赛雷‘}
完整视图代码:
from django.views import View
from students.models import Student
from .serializers import StudentSerializer
from django.http.response import JsonResponse
class StudentView(View):
"""使用序列化器序列化转换单个模型数据"""
def get(self,request,pk):
# 获取数据
student = Student.objects.get(pk=pk)
# 数据转换[序列化过程]
serializer = StudentSerializer(instance=student)
print(serializer.data)
# 响应数据
return JsonResponse(serializer.data)
4)如果要被序列化的是包含多条数据的查询集QuerySet,可以通过添加many=True参数补充说明
"""使用序列化器序列化转换多个模型数据"""
def get(self,request):
# 获取数据
student_list = Student.objects.all()
# 转换数据[序列化过程]
# 如果转换多个模型对象数据,则需要加上many=True
serializer = StudentSerializer(instance=student_list,many=True)
print( serializer.data ) # 序列化器转换后的数据
# 响应数据给客户端
# 返回的json数据,如果是列表,则需要声明safe=False
return JsonResponse(serializer.data,safe=False)
# 访问结果:
# [OrderedDict([(‘id‘, 1), (‘name‘, ‘xiaoming‘), (‘age‘, 20), (‘sex‘, True), (‘description‘, ‘测试‘)]), OrderedDict([(‘id‘, 2), (‘name‘, ‘xiaohui‘), (‘age‘, 22), (‘sex‘, True), (‘description‘, ‘后面来的测试‘)]), OrderedDict([(‘id‘, 4), (‘name‘, ‘小张‘), (‘age‘, 18), (‘sex‘, True), (‘description‘, ‘猴赛雷‘)])]
source和serializers.SerializerMethodField()的用法
# models.py
from django.db import models
class Book(models.Model):
title=models.CharField(max_length=32)
price=models.IntegerField()
pub_date=models.DateField()
publish=models.ForeignKey("Publish",on_delete=models.CASCADE,null=True)
authors=models.ManyToManyField("Author")
def __str__(self):
return self.title
class Publish(models.Model):
name=models.CharField(max_length=32)
email=models.EmailField()
def __str__(self):
return self.name
class Author(models.Model):
name=models.CharField(max_length=32)
age=models.IntegerField()
def __str__(self):
return self.name
# ser.py
from rest_framework import serializers
from app01.models import Book
class BookSerializers(serializers.Serializer):
id=serializers.CharField(read_only=True)
title=serializers.CharField(max_length=32)
price=serializers.IntegerField()
pub_date=serializers.DateField()
# publish=serializers.CharField(source="publish.name",read_only=True)
publish=serializers.CharField(source="publish.name",default=‘xxx‘)
#authors=serializers.CharField(source="authors.all")
authors=serializers.SerializerMethodField(read_only=True)
def get_authors(self,obj):
temp=[]
for author in obj.authors.all():
temp.append(author.name)
return temp
def create(self, validated_data):
print(validated_data)
publish_id=validated_data.get(‘publish‘).get(‘name‘)
print(publish_id)
del validated_data[‘publish‘]
return Book.objects.create(publish_id=publish_id,**validated_data)
def update(self, instance, validated_data):
print(validated_data.get(‘aa‘))
instance.title = validated_data.get(‘title‘, instance.title)
instance.price = validated_data.get(‘price‘, instance.price)
instance.pub_date = validated_data.get(‘pub_date‘, instance.pub_date)
print(validated_data.get(‘publish‘, instance.publish))
instance.publish_id = validated_data.get(‘publish‘, instance.publish).get(‘name‘)
instance.save()
return instance
# views.py
from django.shortcuts import render,HttpResponse
from app01 import models
from django.http import HttpRequest
from rest_framework.views import APIView
from app01.models import Book
from rest_framework.response import Response
from app01.ser import BookSerializers
class BookViewSet(APIView):
def get(self,request,*args,**kwargs):
book_list=Book.objects.all()
# 序列化方式3:
bs=BookSerializers(book_list,many=True) #many=True代表有多条数据,如果只有一条数据,many=False
return Response(bs.data)
def post(self,request,*args,**kwargs):
bs=BookSerializers(data=request.data)
bs.is_valid(raise_exception=True)
# print(bs.validated_data)
bs.save()
return Response(bs.data)
class BookDetailView(APIView):
def get(self,request,pk):
book_obj=models.Book.objects.filter(pk=pk).first()
bs=BookSerializers(book_obj,many=False)
return Response(bs.data)
def put(self,request,pk):
book_obj = models.Book.objects.filter(pk=pk).first()
bs=BookSerializers(instance=book_obj,data=request.data,partial=True)
if bs.is_valid():
bs.save(aa="lqz") # update
return Response(bs.data)
else:
return Response(bs.errors)
def delete(self,request,pk):
models.Book.objects.filter(pk=pk).delete()
return Response("")
# urls.py
from django.contrib import admin
from django.urls import path,re_path
from app01 import views
urlpatterns = [
path(‘admin/‘, admin.site.urls),
path(‘books/‘, views.BookViewSet.as_view()),
re_path(‘books/(?P<pk>\d+)/‘, views.BookDetailView.as_view()),
]
注意:
source 如果是字段,会显示字段,如果是方法,会执行方法,不用加括号(authors=serializers.CharField(source=’authors.all’))
如在模型中定义一个方法,直接可以在在source指定执行
class UserInfo(models.Model):
user_type_choices = (
(1,‘普通用户‘),
(2,‘VIP‘),
(3,‘SVIP‘),
)
user_type = models.IntegerField(choices=user_type_choices)
username = models.CharField(max_length=32,unique=True)
password = models.CharField(max_length=64)
#视图
ret=models.UserInfo.objects.filter(pk=1).first()
aa=ret.get_user_type_display()
#serializer
xx=serializers.CharField(source=‘get_user_type_display‘)
使用序列化器进行反序列化时,需要对数据进行验证后,才能获取验证成功的数据或保存成模型类对象。
在获取反序列化的数据前,必须调用is_valid()方法进行验证,验证成功返回True,否则返回False。
验证失败,可以通过序列化器对象的errors属性获取错误信息,返回字典,包含了字段和字段的错误。如果是非字段错误,可以通过修改REST framework配置中的NON_FIELD_ERRORS_KEY来控制错误字典中的键名。
验证成功,可以通过序列化器对象的validated_data属性获取数据。
在定义序列化器时,指明每个字段的序列化类型和选项参数,本身就是一种验证行为。
如我们前面定义过的BookInfoSerializer
class BookInfoSerializer(serializers.Serializer):
"""图书数据序列化器"""
id = serializers.IntegerField(label=‘ID‘, read_only=True)
btitle = serializers.CharField(label=‘名称‘, max_length=20)
bpub_date = serializers.DateField(label=‘发布日期‘, required=False)
bread = serializers.IntegerField(label=‘阅读量‘, required=False)
bcomment = serializers.IntegerField(label=‘评论量‘, required=False)
image = serializers.ImageField(label=‘图片‘, required=False)
通过构造序列化器对象,并将要反序列化的数据传递给data构造参数,进而进行验证
from booktest.serializers import BookInfoSerializer
data = {‘bpub_date‘: 123}
serializer = BookInfoSerializer(data=data)
serializer.is_valid() # 返回False
serializer.errors
# {‘btitle‘: [ErrorDetail(string=‘This field is required.‘, code=‘required‘)], ‘bpub_date‘: [ErrorDetail(string=‘Date has wrong format. Use one of these formats instead: YYYY[-MM[-DD]].‘, code=‘invalid‘)]}
serializer.validated_data # {}
data = {‘btitle‘: ‘python‘}
serializer = BookInfoSerializer(data=data)
serializer.is_valid() # True
serializer.errors # {}
serializer.validated_data # OrderedDict([(‘btitle‘, ‘python‘)])
is_valid()方法还可以在验证失败时抛出异常serializers.ValidationError,可以通过传递raise_exception=True参数开启,REST framework接收到此异常,会向前端返回HTTP 400 Bad Request响应。
# Return a 400 response if the data was invalid.
serializer.is_valid(raise_exception=True)
如果觉得这些还不够,需要再补充定义验证行为,可以使用以下三种方法:
对<field_name>
字段进行验证,如
class BookInfoSerializer(serializers.Serializer):
"""图书数据序列化器"""
...
def validate_btitle(self, value):
if ‘django‘ not in value.lower():
raise serializers.ValidationError("图书不是关于Django的")
return value
测试
from booktest.serializers import BookInfoSerializer
data = {‘btitle‘: ‘python‘}
serializer = BookInfoSerializer(data=data)
serializer.is_valid() # False
serializer.errors
# {‘btitle‘: [ErrorDetail(string=‘图书不是关于Django的‘, code=‘invalid‘)]}
在序列化器中需要同时对多个字段进行比较验证时,可以定义validate方法来验证,如
class BookInfoSerializer(serializers.Serializer):
"""图书数据序列化器"""
...
def validate(self, attrs):
bread = attrs[‘bread‘]
bcomment = attrs[‘bcomment‘]
if bread < bcomment:
raise serializers.ValidationError(‘阅读量小于评论量‘)
return attrs
测试
from booktest.serializers import BookInfoSerializer
data = {‘btitle‘: ‘about django‘, ‘bread‘: 10, ‘bcomment‘: 20}
s = BookInfoSerializer(data=data)
s.is_valid() # False
s.errors
# {‘non_field_errors‘: [ErrorDetail(string=‘阅读量小于评论量‘, code=‘invalid‘)]}
在字段中添加validators选项参数,也可以补充验证行为,如
def about_django(value):
if ‘django‘ not in value.lower():
raise serializers.ValidationError("图书不是关于Django的")
class BookInfoSerializer(serializers.Serializer):
"""图书数据序列化器"""
id = serializers.IntegerField(label=‘ID‘, read_only=True)
btitle = serializers.CharField(label=‘名称‘, max_length=20, validators=[about_django])
bpub_date = serializers.DateField(label=‘发布日期‘, required=False)
bread = serializers.IntegerField(label=‘阅读量‘, required=False)
bcomment = serializers.IntegerField(label=‘评论量‘, required=False)
image = serializers.ImageField(label=‘图片‘, required=False)
测试:
from booktest.serializers import BookInfoSerializer
data = {‘btitle‘: ‘python‘}
serializer = BookInfoSerializer(data=data)
serializer.is_valid() # False
serializer.errors
# {‘btitle‘: [ErrorDetail(string=‘图书不是关于Django的‘, code=‘invalid‘)]}
前面的验证数据成功后,我们可以使用序列化器来完成数据反序列化的过程.这个过程可以把数据转成模型类对象.
可以通过实现create()和update()两个方法来实现。
class BookInfoSerializer(serializers.Serializer):
"""图书数据序列化器"""
...
def create(self, validated_data):
"""新建"""
return BookInfo(**validated_data)
def update(self, instance, validated_data):
"""更新,instance为要更新的对象实例"""
instance.btitle = validated_data.get(‘btitle‘, instance.btitle)
instance.bpub_date = validated_data.get(‘bpub_date‘, instance.bpub_date)
instance.bread = validated_data.get(‘bread‘, instance.bread)
instance.bcomment = validated_data.get(‘bcomment‘, instance.bcomment)
return instance
如果需要在返回数据对象的时候,也将数据保存到数据库中,则可以进行如下修改
class BookInfoSerializer(serializers.Serializer):
"""图书数据序列化器"""
...
def create(self, validated_data):
"""新建"""
return BookInfo.objects.create(**validated_data)
def update(self, instance, validated_data):
"""更新,instance为要更新的对象实例"""
instance.btitle = validated_data.get(‘btitle‘, instance.btitle)
instance.bpub_date = validated_data.get(‘bpub_date‘, instance.bpub_date)
instance.bread = validated_data.get(‘bread‘, instance.bread)
instance.bcomment = validated_data.get(‘bcomment‘, instance.bcomment)
instance.save()
return instance
实现了上述两个方法后,在反序列化数据的时候,就可以通过save()方法返回一个数据对象实例了
book = serializer.save()
如果创建序列化器对象的时候,没有传递instance实例,则调用save()方法的时候,create()被调用,相反,如果传递了instance实例,则调用save()方法的时候,update()被调用。
from db.serializers import BookInfoSerializer
data = {‘btitle‘: ‘封神演义‘}
serializer = BookInfoSerializer(data=data)
serializer.is_valid() # True
serializer.save() # <BookInfo: 封神演义>
from db.models import BookInfo
book = BookInfo.objects.get(id=2)
data = {‘btitle‘: ‘倚天剑‘}
serializer = BookInfoSerializer(book, data=data)
serializer.is_valid() # True
serializer.save() # <BookInfo: 倚天剑>
book.btitle # ‘倚天剑‘
## models.py
class Book(models.Model):
id=models.AutoField(primary_key=True)
name=models.CharField(max_length=32)
price=models.DecimalField(max_digits=5,decimal_places=2)
author=models.CharField(max_length=32)
publish=models.CharField(max_length=32)
## views.py
from django.shortcuts import render
# Create your views here.
from django.http import JsonResponse
from rest_framework.views import APIView
from app01.models import Book
from app01.ser import BookSerializer
from rest_framework.response import Response #drf 提供的响应对象
# 导入自己写的response类
from app01.utils import MyResponse
class BookView(APIView):
def get(self,request,pk):
book=Book.objects.filter(id=pk).first()
#用一个类,毫无疑问,一定要实例化
#要序列化谁,就把谁传过来
book_ser=BookSerializer(book) # 调用类的__init__
# book_ser.data 序列化对象.data就是序列化后的字典
return Response(book_ser.data)
# return JsonResponse(book_ser.data)
def put(self,request,pk):
response_msg={‘status‘:100,‘msg‘:‘成功‘}
# 找到这个对象
book = Book.objects.filter(id=pk).first()
# 得到一个序列化类的对象
# boo_ser=BookSerializer(book,request.data)
boo_ser=BookSerializer(instance=book,data=request.data)
# 要数据验证(回想form表单的验证)
if boo_ser.is_valid(): # 返回True表示验证通过
boo_ser.save() # 报错
response_msg[‘data‘]=boo_ser.data
else:
response_msg[‘status‘]=101
response_msg[‘msg‘]=‘数据校验失败‘
response_msg[‘data‘]=boo_ser.errors
return Response(response_msg)
def delete(self,request,pk):
response=MyResponse()
ret=Book.objects.filter(pk=pk).delete()
return Response(response.get_dict)
## ser.py
from rest_framework import serializers
from rest_framework.exceptions import ValidationError
# 需要继承 Serializer
from app01.models import Book
def check_author(data):
if data.startswith(‘sb‘):
raise ValidationError(‘作者名字不能以sb开头‘)
else:
return data
class BookSerializer(serializers.Serializer):
id=serializers.CharField(read_only=True)
name=serializers.CharField(max_length=16,min_length=4)
# price=serializers.DecimalField()
price=serializers.CharField(write_only=True,required=True)
author=serializers.CharField(validators=[check_author]) # validators=[] 列表中写函数内存地址
publish=serializers.CharField()
def validate_price(self, data): # validate_字段名 接收一个参数
#如果价格小于10,就校验不通过
# print(type(data))
# print(data)
if float(data)>10:
return data
else:
#校验失败,抛异常
raise ValidationError(‘价格太低‘)
def validate(self, validate_data): # 全局钩子
print(validate_data)
author=validate_data.get(‘author‘)
publish=validate_data.get(‘publish‘)
if author == publish:
raise ValidationError(‘作者名字跟出版社一样‘)
else:
return validate_data
def update(self, instance, validated_data):
#instance是book这个对象
#validated_data是校验后的数据
instance.name=validated_data.get(‘name‘)
instance.price=validated_data.get(‘price‘)
instance.author=validated_data.get(‘author‘)
instance.publish=validated_data.get(‘publish‘)
instance.save() #book.save() django 的orm提供的
return instance
def create(self, validated_data):
instance=Book.objects.create(**validated_data)
return instance
# Book.objects.create(name=validated_data.get(‘name‘))
1) 在对序列化器进行save()保存时,可以额外传递数据,这些数据可以在create()和update()中的validated_data参数获取到
# request.user 是django中记录当前登录用户的模型对象
serializer.save(owner=request.user)
2)默认序列化器必须传递所有required的字段,否则会抛出验证异常。但是我们可以使用partial参数来允许部分字段更新
# Update `comment` with partial data
serializer = CommentSerializer(comment, data={‘content‘: u‘foo bar‘}, partial=True)
如果我们想要使用序列化器对应的是Django的模型类,DRF为我们提供了ModelSerializer模型类序列化器来帮助我们快速创建一个Serializer类。
ModelSerializer与常规的Serializer相同,但提供了:
比如我们创建一个BookInfoSerializer
class BookInfoSerializer(serializers.ModelSerializer):
"""图书数据序列化器"""
class Meta:
model = BookInfo
fields = ‘__all__‘
我们可以在python manage.py shell中查看自动生成的BookInfoSerializer的具体实现
>>> from booktest.serializers import BookInfoSerializer
>>> serializer = BookInfoSerializer()
>>> serializer
BookInfoSerializer():
id = IntegerField(label=‘ID‘, read_only=True)
btitle = CharField(label=‘名称‘, max_length=20)
bpub_date = DateField(allow_null=True, label=‘发布日期‘, required=False)
bread = IntegerField(label=‘阅读量‘, max_value=2147483647, min_value=-2147483648, required=False)
bcomment = IntegerField(label=‘评论量‘, max_value=2147483647, min_value=-2147483648, required=False)
image = ImageField(allow_null=True, label=‘图片‘, max_length=100, required=False)
__all__
表名包含所有字段,也可以写明具体哪些字段,如class BookInfoSerializer(serializers.ModelSerializer):
"""图书数据序列化器"""
class Meta:
model = BookInfo
fields = (‘id‘, ‘btitle‘, ‘bpub_date‘)
class BookInfoSerializer(serializers.ModelSerializer):
"""图书数据序列化器"""
class Meta:
model = BookInfo
exclude = (‘image‘,)
class HeroInfoSerializer(serializers.ModelSerializer):
hbook = BookInfoSerializer()
class Meta:
model = HeroInfo
fields = (‘id‘, ‘hname‘, ‘hgender‘, ‘hcomment‘, ‘hbook‘)
可以通过read_only_fields指明只读字段,即仅用于序列化输出的字段
class BookInfoSerializer(serializers.ModelSerializer):
"""图书数据序列化器"""
class Meta:
model = BookInfo
fields = (‘id‘, ‘btitle‘, ‘bpub_date‘, ‘bread‘, ‘bcomment‘)
read_only_fields = (‘id‘, ‘bread‘, ‘bcomment‘)
我们可以使用extra_kwargs参数为ModelSerializer添加或修改原有的选项参数
class BookInfoSerializer(serializers.ModelSerializer):
"""图书数据序列化器"""
class Meta:
model = BookInfo
fields = (‘id‘, ‘btitle‘, ‘bpub_date‘, ‘bread‘, ‘bcomment‘)
extra_kwargs = {
‘bread‘: {‘min_value‘: 0, ‘required‘: True},
‘bcomment‘: {‘min_value‘: 0, ‘required‘: True},
}
# BookInfoSerializer():
# id = IntegerField(label=‘ID‘, read_only=True)
# btitle = CharField(label=‘名称‘, max_length=20)
# bpub_date = DateField(allow_null=True, label=‘发布日期‘, required=False)
# bread = IntegerField(label=‘阅读量‘, max_value=2147483647, min_value=0, required=True)
# bcomment = IntegerField(label=‘评论量‘, max_value=2147483647, min_value=0, required=True)
标签:自动 数据转换 关于 datetime rom 自己 out 目录 取数
原文地址:https://www.cnblogs.com/chenwenyin/p/13262647.html