詳解從Django Rest Framework響應(yīng)中刪除空字段
我使用django-rest-framework開(kāi)發(fā)了一個(gè)API.
我正在使用ModelSerializer返回模型的數(shù)據(jù).
models.py
class MetaTags(models.Model):
title = models.CharField(_('Title'), max_length=255, blank=True, null=True)
name = models.CharField(_('Name'), max_length=255, blank=True, null=True)
serializer.py
class MetaTagsSerializer(serializers.ModelSerializer): class Meta: model = MetaTags
響應(yīng)
{
"meta": {
"title": null,
"name": "XYZ"
}
}
理想情況下,在API響應(yīng)中,不應(yīng)在響應(yīng)中發(fā)送任何不存在的值.
當(dāng)標(biāo)題為null時(shí),我希望響應(yīng)為:
{
"meta": {
"name": "XYZ"
}
}
您可以嘗試覆蓋to_native函數(shù):
class MetaTagsSerializer(serializers.ModelSerializer):
class Meta:
model = MetaTags
def to_native(self, obj):
"""
Serialize objects -> primitives.
"""
ret = self._dict_class()
ret.fields = self._dict_class()
for field_name, field in self.fields.items():
if field.read_only and obj is None:
continue
field.initialize(parent=self, field_name=field_name)
key = self.get_field_key(field_name)
value = field.field_to_native(obj, field_name)
# Continue if value is None so that it does not get serialized.
if value is None:
continue
method = getattr(self, 'transform_%s' % field_name, None)
if callable(method):
value = method(obj, value)
if not getattr(field, 'write_only', False):
ret[key] = value
ret.fields[key] = self.augment_field(field, field_name, key, value)
return ret
我基本上從serializers.BaseSerializer復(fù)制了基本的to_native函數(shù),并添加了一個(gè)值的檢查.
更新:
至于DRF 3.0,to_native()被重命名為to_representation(),其實(shí)現(xiàn)稍有改變.這是DRF 3.0的代碼,它忽略空值和空字符串值:
def to_representation(self, instance): """ Object instance -> Dict of primitive datatypes. """ ret = OrderedDict() fields = self._readable_fields for field in fields: try: attribute = field.get_attribute(instance) except SkipField: continue # KEY IS HERE: if attribute in [None, '']: continue # We skip `to_representation` for `None` values so that fields do # not have to explicitly deal with that case. # # For related fields with `use_pk_only_optimization` we need to # resolve the pk value. check_for_none = attribute.pk if isinstance(attribute, PKOnlyObject) else attribute if check_for_none is None: ret[field.field_name] = None else: ret[field.field_name] = field.to_representation(attribute) return ret
翻譯自:https://stackoverflow.com/questions/27015931/remove-null-fields-from-django-rest-framework-response
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
- Django的HttpRequest和HttpResponse對(duì)象詳解
- Django使用HttpResponse返回圖片并顯示的方法
- Django使用httpresponse返回用戶頭像實(shí)例代碼
- django rest framework之請(qǐng)求與響應(yīng)(詳解)
- django從請(qǐng)求到響應(yīng)的過(guò)程深入講解
- 從請(qǐng)求到響應(yīng)過(guò)程中django都做了哪些處理
- Django框架的使用教程路由請(qǐng)求響應(yīng)的方法
- 在Python的Django框架中用流響應(yīng)生成CSV文件的教程
- Django 中使用流響應(yīng)處理視頻的方法
- Django 響應(yīng)數(shù)據(jù)response的返回源碼詳解
- django創(chuàng)建簡(jiǎn)單的頁(yè)面響應(yīng)實(shí)例教程
- Django框架HttpResponse對(duì)象用法實(shí)例分析
相關(guān)文章
python實(shí)現(xiàn)中文轉(zhuǎn)換url編碼的方法
這篇文章主要介紹了python實(shí)現(xiàn)中文轉(zhuǎn)換url編碼的方法,結(jié)合實(shí)例形式分析了Python針對(duì)中文的gbk與utf-8編碼轉(zhuǎn)換的相關(guān)技巧,具有一定參考借鑒價(jià)值,需要的朋友可以參考下2016-06-06
基于OpenCV目標(biāo)跟蹤實(shí)現(xiàn)人員計(jì)數(shù)器
這篇文章主要介紹了如何利用Python OpenCV這兩者來(lái)創(chuàng)建更準(zhǔn)確的人員計(jì)數(shù)器,文中的示例代碼講解詳細(xì),感興趣的小伙伴快來(lái)跟隨小編學(xué)習(xí)一下吧2022-03-03
python opencv檢測(cè)直線 cv2.HoughLinesP的實(shí)現(xiàn)
cv2.HoughLines()函數(shù)是在二值圖像中查找直線,本文結(jié)合示例詳細(xì)的介紹了cv2.HoughLinesP的用法,感興趣的可以了解一下2021-06-06
Python網(wǎng)絡(luò)編程之Python編寫TCP協(xié)議程序的步驟
這篇文章主要介紹了Python網(wǎng)絡(luò)編程編寫TCP協(xié)議程序的開(kāi)發(fā)步驟,通過(guò)實(shí)例代碼介紹了TCP客戶端程序開(kāi)發(fā),案例講解多任務(wù)版TCP服務(wù)端程序開(kāi)發(fā),需要的朋友可以參考下2022-11-11
基于python介紹pytorch保存和恢復(fù)參數(shù)
這篇文章主要介紹了基于python介紹pytorch保存和恢復(fù)參數(shù),為了恢復(fù)模型,我們需要用代碼生成框架,然后從磁盤加載參數(shù),下面具體的相關(guān)介紹,需要的小伙伴可以參考一下2022-03-03
Python中dumps與dump及l(fā)oads與load的區(qū)別
這篇文章主要介紹了Python中dumps與dump、loads與load的區(qū)別,json模塊提供了一種很簡(jiǎn)單的方式來(lái)編碼和解碼JSON數(shù)據(jù)。其中兩個(gè)主要的函數(shù)是json.dumps()和json.loads(),需要的朋友可以參考下2022-04-04

