django自定义序列化返回处理数据为null情况
在接口返回数据时,如果数据库表中查询出来的某些字段为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