django自定義序列化返回處理資料為null情況
阿新 • • 發佈:2019-01-09
在介面返回資料時,如果資料庫表中查詢出來的某些欄位為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