Django RestFramework 自定义字段返回

在接口返回数据时,如果数据库表中查询出来的某些字段为null时,在前端需要多处理一些数据异常的情况。
django可以自定义序列化返回处理,将返回的内容限制和预处理再返回到前端。

1.未处理时返回

如图上,有email、mobile这两个字段是有可以为空且默认值为null的。

2.to_representation处理
在模型序列化类增加, to_representation方法,以自定义数据处理限制

from rest_framework import serializers
from .models import UserInfo

class UserInfoSerializer(serializers.ModelSerializer):
    class Meta:
        model = UserInfo
        # fields = '__all__'
        fields = (
            'id', 'email', 'date_create', 'mobile', 'email', 'notice_voice', 'notice_email', 'notice_sms',
            'notice_push')

    def to_representation(self, instance):
        data = super().to_representation(instance)
        if not data['email']:
            data['email'] = ""
        if not data['mobile']:
            data['mobile'] = ""
        return data



3.处理后前端获取

django python

————————————————
版权声明:本文为CSDN博主「陌生谁家年少」的原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/u010277446/article/details/86151809

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值