drf-序列化组件

发布时间:2023年12月21日

序列化类常用字段

除了CharField 以外,还要很多别的---》表模型中 ?models.CharField ?--->基本一一对应
如果跟 表模型中对不上:你统一用 ?CharField

字段字段构造方式
BooleanFieldBooleanField()
NullBooleanFieldNullBooleanField()
CharFieldCharField(max_length=None, min_length=None, allow_blank=False, trim_whitespace=True)
EmailFieldEmailField(max_length=None, min_length=None, allow_blank=False)
RegexFieldRegexField(regex, max_length=None, min_length=None, allow_blank=False)
SlugFieldSlugField(maxlength=50, min_length=None, allow_blank=False) 正则字段,验证正则模式 [a-zA-Z0-9-]+
URLFieldURLField(max_length=200, min_length=None, allow_blank=False)
UUIDFieldUUIDField(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"
IPAddressFieldIPAddressField(protocol=’both’, unpack_ipv4=False, **options)
IntegerFieldIntegerField(max_value=None, min_value=None)
FloatFieldFloatField(max_value=None, min_value=None)
DecimalFieldDecimalField(max_digits, decimal_places, coerce_to_string=None, max_value=None, min_value=None) max_digits: 最多位数 decimal_palces: 小数点位置
DateTimeFieldDateTimeField(format=api_settings.DATETIME_FORMAT, input_formats=None)
DateFieldDateField(format=api_settings.DATE_FORMAT, input_formats=None)
TimeFieldTimeField(format=api_settings.TIME_FORMAT, input_formats=None)
DurationFieldDurationField()
ChoiceFieldChoiceField(choices) choices与Django的用法相同
MultipleChoiceFieldMultipleChoiceField(choices)
FileFieldFileField(max_length=None, allow_empty_file=False, use_url=UPLOADED_FILES_USE_URL)
ImageFieldImageField(max_length=None, allow_empty_file=False, use_url=UPLOADED_FILES_USE_URL)
ListFieldListField(child=, min_length=None, max_length=None)
DictFieldDictField(child=)

序列化字段常用参数

字段参数

CharField(max_length=None, min_length=None, allow_blank=False, trim_whitespace=True)
  1. max_length :校验,最大长度
  2. min_length:校验最短长度
  3. allow_blank:是否允许为空
  4. trim_whitespace:去掉前后的空白
DateTimeField(format=api_settings.DATETIME_FORMAT)
  1. format:格式化成的样子
IntegerField(max_value=None, min_value=None)
  1. max_value :最大值
  2. 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页面时,显示的字段帮助提示信息

字段校验有四层

  1. 字段自己
  2. validators校验 ?忽略
  3. 局部钩子
  4. 全局钩子

序列化高级用法之soruce

修改项目名字

修改文件夹名
修改项目名
能顺利运行,按照如下图操作
如果改了文件夹名,全局替换

Rename directory:只改文件夹的名字不改项目名

Rename project:该项目名

两个都需要去改

然后在配置

然后更改文件名后进行全局替换

source使用

修改字段,映射字段

publish_name表中不存在
publish_name = serializers.CharField(source='name')

修改字段,映射方法

sb_name是表模型中一个方法
name = serializers.CharField(source='sb_name')

修改字段,跨表查询

book表中可以链表查询
publish=models.ForeignKey(to='Publish.name')

序列化高级用法之定制返回字段

定制序列化返回的字段格式

	-方案一:在表模型中写,在序列化类中映射  (可以使用source)
    	# models.py
        def publish_detail(self):
        	return {'name': self.publish.name, 'city': self.publish.city}
        # serializer.py
        	publish_detail = serializers.DictField()
        # 前端看到
            "publish_detail": {
                "name": "北京出版本是",
                "city": "北京"
            }
    -方案二:在序列化类中写SerializerMethodField,必须配合一个方法 get_字段名,方法返回什么,前端就看到什么
    	# Serializer.py
            publish_detail = serializers.SerializerMethodField()
            def get_publish_detail(self, obj):
                return {'name': obj.publish.name, 'city': obj.publish.city}
        # 前端看到
            "publish_detail": {
                "name": "北京出版本是",
                "city": "北京"
            }
  • models.py
from django.db import models


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')

    def __str__(self):
        return self.name
    # def book_name(self):
    #     return self.name+'sb'
    # def publish_detail(self):
    #     return {'name': self.publish.name, 'city': self.publish.city}
    #
    # def author_list(self):
    #     l = []
    #     for author in self.authors.all():
    #         l.append({'name': author.name, 'age': author.age})
    #     return l


class Author(models.Model):
    name = models.CharField(max_length=32)
    age = models.IntegerField()
    author_detail = models.OneToOneField(to='AuthorDetail', on_delete=models.CASCADE)

    def __str__(self):
        return self.name


class AuthorDetail(models.Model):
    telephone = models.BigIntegerField()
    birthday = models.DateField()
    addr = models.CharField(max_length=64)


class Publish(models.Model):
    name = models.CharField(max_length=32)
    city = models.CharField(max_length=32)
    email = models.EmailField()

    def __str__(self):
        return self.name

    class Meta:
        verbose_name = '出版社'
        verbose_name_plural = verbose_name
  • views.py
class BookView(APIView):
    def get(self, request):
        obj = Book.objects.all()
        ser = BookSerializer(instance=obj, many=True)

        '''
        [
            {
                "name": "西游记",
                "price": "66.00",
                "publish_detail": {name:名字,city:城市},
                "authors_list":[{name:名字,age:19}]
            },
    
        ]
        
        '''
        return Response(ser.data)
  • serializer.py
### 定制返回字段
class BookSerializer(serializers.Serializer):
    name = serializers.CharField()
    price = serializers.CharField()
    #### 定制返回字段---》方案一:在表模型中写方法,在序列化类中做映射
    # publish_detail = serializers.CharField()  # publish_detail 会映射表模型中 publish_detail方法,方法返回值是 字典,强行用CharField字符串接收
    # publish_detail = serializers.DictField()  # publish_detail 会映射表模型中 publish_detail方法,方法返回值是 字典,用DictField接收
    # author_list = serializers.ListField()

    ###定制返回字段---》方案二:在序列化类中写  SerializerMethodField
    # 只要写了这个字段类SerializerMethodField,必须配合一个方法:get_字段名,这个方法返回什么,前端这个字段就显示什么
    publish_detail = serializers.SerializerMethodField()

    def get_publish_detail(self, obj):
        # 当前序列化到的book对象
        return {'name': obj.publish.name, 'city': obj.publish.city}

    author_list = serializers.SerializerMethodField()

    def get_author_list(self, obj):
        l = []
        for author in obj.authors.all():
            l.append({'name': author.name, 'age': author.age})
        return l

    book_name = serializers.SerializerMethodField()
	
    def get_book_name(self, obj):
        return obj.name + 'sb'

?

多表关联反序列化

反序列化保存
使用同一个序列化类会出现

  • 序列化字段和反序列化字段不一致
  • 序列化字段
    • name
    • price
    • publish_detail
    • author_list
  • 反序列化字段:
    • name
    • price
    • publish
    • author
  • 如果是共同的,不需要额外处理
  • 如果是不同的,需要通过字段参数控制
    • read_only?? ?表明该字段仅用于序列化输出,默认False,序列化过程
    • write_only?? ?表明该字段仅用于反序列化输入,默认False,反序列化过程

  • serializer.py

class BookSerializer(serializers.Serializer):
    name = serializers.CharField()  # 公共的
    price = serializers.CharField()  # 公共的
    publish = serializers.IntegerField(write_only=True)  # 只用来做反序列化
    authors = serializers.ListField(write_only=True)  # 只用来做反序列化

    publish_detail = serializers.SerializerMethodField(read_only=True)  # 只用来做序列化
    author_list = serializers.SerializerMethodField(read_only=True)  # 只用来做序列化

    def get_publish_detail(self, obj):
        return {'name': obj.publish.name, 'city': obj.publish.city}

    def get_author_list(self, obj):
        l = []
        for author in obj.authors.all():
            l.append({'name': author.name, 'age': author.age})
        return l

    def create(self, validated_data):
        # {name,price,publish:1,authors:[1,2]}
        authors = validated_data.pop('authors')
        book = Book.objects.create(name=validated_data.get('name'), price=validated_data.get('price'),
                                   publish_id=validated_data.get('publish'))
        book.authors.add(*authors)
        return book

    def update(self, instance, validated_data):
        # {name,price,publish:1,authors:[1,2]}
        authors = validated_data.pop('authors')
        validated_data['publish_id'] = validated_data.pop('publish')
        for key in validated_data:
            setattr(instance, key, validated_data[key])

        instance.save()
        # 先清空在放入
        # instance.authors.clear()
        # instance.authors.add(*authors)
        # 直接存
        instance.authors.set(authors)
        return instance
  • views.py
class BookView(APIView):

    def post(self, request):
        ser = BookSerializer(data=request.data)
        if ser.is_valid():
            ser.save()
            return Response(ser.data)
        else:
            return Response(ser.errors)


class BookDetail(APIView):
    def put(self, request, pk):
        book = Book.objects.filter(pk=pk).first()
        ser = BookSerializer(instance=book, data=request.data)
        if ser.is_valid():
            ser.save()
            return Response(ser.data)
        else:
            return Response(ser.errors)
  • urls.py
urlpatterns = [
    path('books/', views.BookView.as_view()),
    path('books/<int:pk>/', views.BookDetail.as_view()),
]

?

ModelSerializer使用

之前写的序列化类,继承了serializers.Serializer,跟表没有必然联系
ModelSerializer跟表一一对应,以后基本需要重写create和update

  • serializer.py
### 继承ModelSerializer--->少写代码
class BookSerializer(serializers.ModelSerializer):
    name = serializers.CharField(max_length=18,min_length=3)  # 公共的
    price = serializers.CharField()  # 公共的
    publish = serializers.IntegerField(write_only=True)  # 只用来做反序列化
    authors = serializers.ListField(write_only=True)  # 只用来做反序列化
    # 上述操作,通过 Meta实现了

    # 扩写的字段,也要在fields注册
    # 方式二:定制字段
    publish_detail = serializers.SerializerMethodField(read_only=True)  # 只用来做序列化
    author_list = serializers.SerializerMethodField(read_only=True)  # 只用来做序列化
    def get_publish_detail(self, obj):
        return {'name': obj.publish.name, 'city': obj.publish.city}
    def get_author_list(self, obj):
        l = []
        for author in obj.authors.all():
            l.append({'name': author.name, 'age': author.age})
        return l

    # 方式二:定制字段方式一
    publish_detail = serializers.DictField(read_only=True)
    author_list = serializers.ListField(read_only=True)
    class Meta:
        model = Book  # 写了这两句,会把表模型中Book,所有字段映射过来
        # fields='__all__'
        fields = ['name', 'price', 'publish', 'authors', 'publish_detail', 'author_list']
        extra_kwargs = {  # 给某个或某几个字段设置字段属性
            'name': {'max_length': 18, 'min_length': 3},
            'publish': {'write_only': True},
            'authors': {'write_only': True},
            'publish_detail': {'read_only': True},
            'author_list': {'read_only': True},
        }

    # 一般不需要写create和update了---》ModelSerializer帮咱们实现了
    # 局部钩子和全局钩子,该怎么写还怎么写
    def validate_name(self,name):
        pass

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