zoukankan      html  css  js  c++  java
  • 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

     待续

  • 相关阅读:
    隐藏QQ全部图标,隐藏QQ全部信息
    发放腾讯微博邀请,先到先得、
    关于“5005: 优化字节代码时发生未知错误。”的处理办法
    端口
    xmldocument
    MasterPage
    asp.net ajax
    mysqladmin 设置用户名初始密码报错you need the SUPER privilege for this operation
    实践SSH通道链接国外服务器访问受限网站
    转载 实践与分享:Windows 7怎么获取TrustedInstaller权限【图文教程】
  • 原文地址:https://www.cnblogs.com/52forjie/p/10110481.html
Copyright © 2011-2022 走看看