一、序列化类的常用字段和字段参数
常用字段
字段名 | 字段参数 |
---|---|
CharField | max_length=None, min_length=None, allow_blank=False, trim_whitespace=True |
IntegerField | max_value=None, min_value=None |
FloatField | max_value=None, min_value=None |
BooleanField | |
NullBooleanField | |
FloatField | max_value=None, min_value=None |
DecimalField | max_digits, decimal_places, coerce_to_string=None, max_value=None, min_value=None 注:max_digits: 最多位数 decimal_palces: 小数点位置 |
TimeField | format=api_settings.TIME_FORMAT, input_formats=None |
DateField | format=api_settings.DATE_FORMAT, input_formats=None |
DateTimeField | format=api_settings.DATETIME_FORMAT, input_formats=None) |
EmailField | max_length=None, min_length=None, allow_blank=False |
RegexField | regex, max_length=None, min_length=None, allow_blank=False |
SlugField | max_length=50, min_length=None, allow_blank=False),正则字段,验证正则模式 [a-zA-Z0-9-]+ |
URLField | max_length=200, min_length=None, allow_blank=False |
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 | protocol=’both’, unpack_ipv4=False, **options) |
DurationField | |
ChoiceField | choices,choices与Django的用法相同 |
MultipleChoiceField | choices |
FileField | max_length=None, allow_empty_file=False, use_url=UPLOADED_FILES_USE_URL |
ImageField | max_length=None, allow_empty_file=False, use_url=UPLOADED_FILES_USE_URL |
ListField | child=, min_length=None, max_length=None |
DictField | child= |
常用字段参数
CharField及子类的(EmailField)
反序列化的校验,字段自己的规则
参数 | 含义 |
---|---|
max_length | 最大长度 |
min_lenght | 最小长度 |
allow_blank | 是否允许为空 |
trim_whitespace | 是否截断空白字符 |
IntegerField
参数 | 含义 |
---|---|
max_value | 最小值 |
max_value | 最大值 |
字段共有参数
参数 | 含义 |
---|---|
required | 表明该字段在反序列化时必须输入,默认True |
default | 反序列化时使用的默认值 |
allow_null | 表明该字段是否允许传入None,默认False |
validators | 该字段使用的验证器 |
error_messages | 包含错误编号与错误信息的字典 |
label | 于HTML展示API页面时,显示的字段名称 |
help_text | 用于HTML展示API页面时,显示的字段帮助提示信息 |
read_only | 表明该字段仅用于序列化输出,默认False |
write_only | 表明该字段仅用于反序列化输入,默认False |
二、序列化高级用法之source(了解)
首先先创建一个django项目,创建book表、publish表、以及author表,并建立三个表之间的关系,完成模型表数据的迁移并录入数据
from django.db import models# Create your models here.class Book(models.Model):name = models.CharField(max_length=32)price = models.DecimalField(max_digits=5, decimal_places=2)# 外键字段书与出版社一对多,关联字段在多的一方publish = models.ForeignKey(to='Publish', on_delete=models.CASCADE)# 书与作者多对多,需要创建中间表,使用全自动创建第三张表authors = models.ManyToManyField(to='Author')class Publish(models.Model):name = models.CharField(max_length=32)addr = models.CharField(max_length=64)class Author(models.Model):name = models.CharField(max_length=32)phone = models.IntegerField()
序列化字段名
sourse
- 可以定制序列化字段名
- 防止数据被人篡盗,将前端展示的字段名和后端数据的字段名设置成不同的字段名
sourse序列化自有字段和关联字段的区别
1.自有字段,直接写表字段名
publish_name = serializers.CharField(max_length=12, min_length=3, required=True, allow_blank=True,source='name')2.还可以直接映射方法
models.py
class Publish(models.Model):name = models.CharField(max_length=32)addr = models.CharField(max_length=64)def sb_name(self):return self.name+'sb'serializer.py
publish_name = serializers.CharField(max_length=12, min_length=3, required=True, allow_blank=True,source='sb_name')3.关联字段 通过外键获取一对多 一对多的关联,直接点publish=serializers.CharField(max_length=8,source='publish.name')多对多 source不能用实现定制序列化关联表的字段authors = serializers.CharField(source='authors.all')
作业之装饰器
def outer(func):def inner(request, *args, **kwargs):try:request.data = json.loads(request.body) # 如果json格式不可以序列化loadsexcept Exception as e:request.data = request.POSTif request.method == 'PUT':body_in = str(request.body, encoding='utf-8') # 转 译body_in = parse.unquote(body_in)# request.data = {i.split('=')[0]: i.split('=')[1] for i in body_in.split('&')} # 字典推导式# 笨方法d = {}sp_1 = body_in.split('&')for i in sp_1:k, v = i.split('=')d[k] = vrequest.data = dres = func(request, *args, **kwargs)return resreturn inner@outer
def index(request):print(request.data)return JsonResponse({'code': '请求成功'})该装饰器只针对视图函数,如果要装饰在类的方法上就需要添加形参中添加self参数
作业之用户一次性提交数据
views.pyfrom .serializer import AuthorSerializerclass AuthorView(APIView):def post(self, request):ser = AuthorSerializer(data=request.data)if ser.is_valid():ser.save()return Response({'code': 100, 'msg': '创建成功'})else:return Response({'code': 100, 'msg': ser.errors})
serializer.pyclass AuthorSerializer(serializers.ModelSerializer):telephone = serializers.CharField()birthday = serializers.CharField()addr = serializers.CharField()class Meta:model = Authorfields = ['name', 'age', 'telephone', 'birthday', 'addr']def create(self, validated_data): # 因为author表里没有authordetail其它三个字段,需要重写telephone = validated_data.pop('telephone')birthday = validated_data.pop('birthday')addr = validated_data.pop('addr')# 先创建作者详情,在创建作者,因为外键字段的约束,是现有作者详情,再有作者约束author_detail = AuthorDetail.objects.create(telephone=telephone, birthday=birthday, addr=addr)validated_data['author_detail'] = author_detailauthor = Author.objects.create(**validated_data)return author