Django之DRF框架三,序列化组件

2023-12-24 16:38:30

一、序列化类的常用字段和字段参数

常用字段

字段名字段参数
CharFieldmax_length=None, min_length=None, allow_blank=False, trim_whitespace=True
IntegerFieldmax_value=None, min_value=None
FloatFieldmax_value=None, min_value=None
BooleanField
NullBooleanField
FloatFieldmax_value=None, min_value=None
DecimalFieldmax_digits, decimal_places, coerce_to_string=None, max_value=None, min_value=None 注:max_digits: 最多位数 decimal_palces: 小数点位置
TimeFieldformat=api_settings.TIME_FORMAT, input_formats=None
DateFieldformat=api_settings.DATE_FORMAT, input_formats=None
DateTimeFieldformat=api_settings.DATETIME_FORMAT, input_formats=None)
EmailFieldmax_length=None, min_length=None, allow_blank=False
RegexFieldregex, max_length=None, min_length=None, allow_blank=False
SlugFieldmax_length=50, min_length=None, allow_blank=False),正则字段,验证正则模式 [a-zA-Z0-9-]+
URLFieldmax_length=200, min_length=None, allow_blank=False
UUIDFieldformat=’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”
IPAddressFieldprotocol=’both’, unpack_ipv4=False, **options)
DurationField
ChoiceFieldchoices,choices与Django的用法相同
MultipleChoiceFieldchoices
FileFieldmax_length=None, allow_empty_file=False, use_url=UPLOADED_FILES_USE_URL
ImageFieldmax_length=None, allow_empty_file=False, use_url=UPLOADED_FILES_USE_URL
ListFieldchild=, min_length=None, max_length=None
DictFieldchild=

常用字段参数

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格式不可以序列化loads
        except Exception as e:
            request.data = request.POST
            if 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] = v
                request.data = d
        res = func(request, *args, **kwargs)
        return res

    return inner


@outer
def index(request):
    print(request.data)
    return JsonResponse({'code': '请求成功'})

该装饰器只针对视图函数,如果要装饰在类的方法上就需要添加形参中添加self参数

作业之用户一次性提交数据

views.py

from .serializer import AuthorSerializer


class 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.py

class AuthorSerializer(serializers.ModelSerializer):
    telephone = serializers.CharField()
    birthday = serializers.CharField()
    addr = serializers.CharField()

    class Meta:
        model = Author
        fields = ['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_detail
        author = Author.objects.create(**validated_data)

        return author

文章来源:https://blog.csdn.net/shiyaopeng11/article/details/135132065
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。