• django drf 的serializer源码分析


    1,一般我们都是实例化调用data方法开始

    dimension_serializer = self.get_serializer(
                instance=queryset, many=True).data

    按继承关系,是调用serializer的data方法

    @property
        def data(self):
            ret = super(Serializer, self).data
            return ReturnDict(ret, serializer=self)
    
    而serializer的会调用父类BaseSerializer的data方法
    @property
        def data(self):
            if hasattr(self, 'initial_data') and not hasattr(self, '_validated_data'):
                msg = (
                    'When a serializer is passed a `data` keyword argument you '
                    'must call `.is_valid()` before attempting to access the '
                    'serialized `.data` representation.
    '
                    'You should either call `.is_valid()` first, '
                    'or access `.initial_data` instead.'
                )
                raise AssertionError(msg)
    
            if not hasattr(self, '_data'):
                if self.instance is not None and not getattr(self, '_errors', None):
                    self._data = self.to_representation(self.instance)
                elif hasattr(self, '_validated_data') and not getattr(self, '_errors', None):
                    self._data = self.to_representation(self.validated_data)
                else:
                    self._data = self.get_initial()
            return self._data
    
    

    2,按运行的顺序,现在会运行self.to_representation方法,

    所以现在调用serializer里面的to_representation方法

        def to_representation(self, instance):
            """
            Object instance -> Dict of primitive datatypes.
            """
            ret = OrderedDict()
            fields = self._readable_fields             #获取我们所写的serializer下面的所有fields,  例: OrderedDict([('m1_overdue_rate', SerializerMethodField()),]
    
            for field in fields:
                try:
                    attribute = field.get_attribute(instance)
                except SkipField:
                    continue
    
                # We skip `to_representation` for `None` values so that fields do
                # not have to explicitly deal with that case.
                #
                # For related fields with `use_pk_only_optimization` we need to
                # resolve the pk value.
                check_for_none = attribute.pk if isinstance(attribute, PKOnlyObject) else attribute
                if check_for_none is None:
                    ret[field.field_name] = None
                else:
                    ret[field.field_name] = field.to_representation(attribute)
    
            return ret

     待续

  • 相关阅读:
    Python那些优雅的写法:switch-case
    python将print输出的信息保留到日志文件中
    Python 获取被调用函数名称,所处模块,被调用代码行
    python **运算符及多参数传参
    使用Docker之镜像的拉取、查询、删除
    资料
    kmp算法
    开源软件
    golang之http请求的dns解析代码流程
    Go语言从HTTP请求中获取服务端IP地址
  • 原文地址:https://www.cnblogs.com/52forjie/p/10110481.html
Copyright © 2020-2023  润新知