Django rest framework 改变序列化返回的数据

在使用Django rest framework的serializer时遇到一个问题:

  1. 数据库里存的是时间戳,但是前端想要直接处理好的日期格式("%Y-%m-%d %H:%M:%S")。
class ProductsSerializer(serializers.ModelSerializer):
    # 项目数据序列化器

    class Meta:
        model = Products
        fields = '__all__'  # 返回所有字段

    def to_representation(self, instance):
        data = super().to_representation(instance)
        # data['create_time']获取到数据库里存储的时间戳,然后用localtime()函数转换为localtime
        time_local = time.localtime(data['create_time'])
        # 拿到转换后的time_local再用strftime()函数重新格式化时间
        data['create_time'] = time.strftime("%Y-%m-%d %H:%M:%S", time_local)
        # 返回处理之后的数据
        return data

处理之后返回的数据:在这里插入图片描述
源码剖析:

    def to_representation(self, instance):
        """
        Object instance -> Dict of primitive datatypes.
        """
        ret = OrderedDict()
        fields = self._readable_fields   # 读取我们所写的serializer下面的所有fields

        for field in fields:
            try:
                attribute = field.get_attribute(instance)  # 获取实例中对应的field字段
            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)  # 否则调用field的to_representation来处理attribute

        return ret    # 返回结果

总结:
这里我们用到了.to_representation(self, obj) - 重写此方法来改变读取操作的序列化结果。

你可能感兴趣的:(Django)