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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章