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) - 重写此方法来改变读取操作的序列化结果。

  • 4
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值