在接口返回數據時,如果數據庫表中查詢出來的某些字段爲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.處理後前端獲取
————————————————
版權聲明:本文爲CSDN博主「陌生誰家年少」的原創文章,遵循 CC 4.0 BY-SA 版權協議,轉載請附上原文出處鏈接及本聲明。
原文鏈接:https://blog.csdn.net/u010277446/article/details/86151809