# @Author : Rocky # @File : serializers.py # @Time : 2023/7/24 13:35 from rest_framework.serializers import ModelSerializer, SerializerMethodField from background.models import ProductInfo, VideoInfo, QuickStartInfo, UpgradeFirmwareInfo class ReadWriteSerializerMethodField(SerializerMethodField): """ 支持可读写的SerializerMethodField 可实现Model字段和Serializer字段更加灵活地解绑 通过实现get_xxxfield方法,实现从Model的某个字段读值映射到Serializer对应字段 通过实现set_xxxfield方法,实现从Serializer字段回填值到Model对应字段 """ def __init__(self, method_name=None, write_method_name=None, **kwargs): self.method_name = method_name self.write_method_name = write_method_name kwargs["source"] = "*" super(SerializerMethodField, self).__init__(**kwargs) def bind(self, field_name, parent): # 绑定读函数 get_{field_name} 和写函数 set_{field_name} default_method_name = f"get_{field_name}" default_write_method_name = f"set_{field_name}" if self.method_name is None: self.method_name = default_method_name if self.write_method_name is None: self.write_method_name = default_write_method_name super(SerializerMethodField, self).bind(field_name, parent) def to_representation(self, value): # 读取过程hook method = getattr(self.parent, self.method_name) return method(value) def to_internal_value(self, data): # 写入过程hook method = getattr(self.parent, self.write_method_name) return method(data) class ProductInfoSerializer(ModelSerializer): class Meta: model = ProductInfo fields = '__all__' class VideoInSerializer(ModelSerializer): class Meta: model = VideoInfo fields = '__all__' class QuickStartInfoSerializer(ModelSerializer): class Meta: model = QuickStartInfo fields = '__all__' def create(self, validated_data): link = validated_data.get('link') validated_data['link'] = 'https://ansjerfilemanager.s3.amazonaws.com/vsees/quick_start_file/{}'.format(link) video_qs = VideoInfo.objects.create(**validated_data) return video_qs def update(self, instance, validated_data): link = 'https://ansjerfilemanager.s3.amazonaws.com/vsees/quick_start_file/{}'.format(validated_data.get('link')) instance.link = link instance.save() return instance class UpgradeFirmwareInfoSerializer(ModelSerializer): class Meta: model = UpgradeFirmwareInfo fields = '__all__' def create(self, validated_data): link = validated_data.get('link') validated_data['link'] = 'https://ansjerfilemanager.s3.amazonaws.com/vsees/upgrade_firmware_file/{}'.format( link) video_qs = VideoInfo.objects.create(**validated_data) return video_qs def update(self, instance, validated_data): link = 'https://ansjerfilemanager.s3.amazonaws.com/vsees/upgrade_firmware_file/{}'.format( validated_data.get('link')) instance.link = link instance.save() return instance