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.\n'
                '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

 

 待续

 

转载于:https://www.cnblogs.com/52forjie/p/10110481.html

你可能感兴趣的:(django drf 的serializer源码分析)