django 解決自定義序列化返回處理數(shù)據(jù)為null的問題
在接口返回數(shù)據(jù)時,如果數(shù)據(jù)庫表中查詢出來的某些字段為null時,在前端需要多處理一些數(shù)據(jù)異常的情況。
django可以自定義序列化返回處理,將返回的內(nèi)容限制和預(yù)處理再返回到前端。
1.未處理時返回
如圖上,有email、mobile這兩個字段是有可以為空且默認(rèn)值為null的。
2.to_representation處理
在模型序列化類增加, to_representation方法,以自定義數(shù)據(jù)處理限制
from rest_framework import serializersfrom .models import UserInfoclass 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.處理后前端獲取
補(bǔ)充知識:Django query查詢正常,返回對象為空QuerySet
我出現(xiàn)這個錯誤的前提條件:
數(shù)據(jù)為導(dǎo)入的數(shù)據(jù),并不是正常從前端添加入庫的。
問題現(xiàn)象:
views里獲取數(shù)據(jù)庫查詢對象集合 obj= models.表名.objects.filter(**kwargs)
控制臺debug發(fā)現(xiàn) obj為QuerySet<[]>
拿著query到數(shù)據(jù)庫里執(zhí)行sql ,還能查出數(shù)據(jù),就是沒返回
解決問題:
查看數(shù)據(jù)庫字段是否符合models中定義的格式,如,是否有默認(rèn)值,
將數(shù)據(jù)庫為空字段修改成和models一樣的,有個快速比對的方法,從前端向數(shù)據(jù)庫添加一條數(shù)據(jù),拿這個正式數(shù)據(jù)和導(dǎo)入數(shù)據(jù)做比對,哪里不一樣,修改哪里即可。
以上這篇django 解決自定義序列化返回處理數(shù)據(jù)為null的問題就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. JSP取得在WEB.XML中定義的參數(shù)2. XML 非法字符(轉(zhuǎn)義字符)3. 關(guān)于html嵌入xml數(shù)據(jù)島如何穿過樹形結(jié)構(gòu)關(guān)系的問題4. el-input無法輸入的問題和表單驗(yàn)證失敗問題解決5. .NET Framework各版本(.NET2.0 3.0 3.5 4.0)區(qū)別6. CSS3實(shí)例分享之多重背景的實(shí)現(xiàn)(Multiple backgrounds)7. 不要在HTML中濫用div8. vue實(shí)現(xiàn)復(fù)制文字復(fù)制圖片實(shí)例詳解9. XML入門的常見問題(三)10. 前端html+css實(shí)現(xiàn)動態(tài)生日快樂代碼
