1. 程式人生 > >django drf 的serializer原始碼分析

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

 

 待續