詳解從Django Rest Framework響應中刪除空字段
我使用django-rest-framework開發(fā)了一個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
響應
{
"meta": {
"title": null,
"name": "XYZ"
}
}
理想情況下,在API響應中,不應在響應中發(fā)送任何不存在的值.
當標題為null時,我希望響應為:
{
"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復制了基本的to_native函數(shù),并添加了一個值的檢查.
更新:
至于DRF 3.0,to_native()被重命名為to_representation(),其實現(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
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
- Django的HttpRequest和HttpResponse對象詳解
- Django使用HttpResponse返回圖片并顯示的方法
- Django使用httpresponse返回用戶頭像實例代碼
- django rest framework之請求與響應(詳解)
- django從請求到響應的過程深入講解
- 從請求到響應過程中django都做了哪些處理
- Django框架的使用教程路由請求響應的方法
- 在Python的Django框架中用流響應生成CSV文件的教程
- Django 中使用流響應處理視頻的方法
- Django 響應數(shù)據(jù)response的返回源碼詳解
- django創(chuàng)建簡單的頁面響應實例教程
- Django框架HttpResponse對象用法實例分析
相關文章
基于OpenCV目標跟蹤實現(xiàn)人員計數(shù)器
這篇文章主要介紹了如何利用Python OpenCV這兩者來創(chuàng)建更準確的人員計數(shù)器,文中的示例代碼講解詳細,感興趣的小伙伴快來跟隨小編學習一下吧2022-03-03
python opencv檢測直線 cv2.HoughLinesP的實現(xiàn)
cv2.HoughLines()函數(shù)是在二值圖像中查找直線,本文結合示例詳細的介紹了cv2.HoughLinesP的用法,感興趣的可以了解一下2021-06-06
Python網(wǎng)絡編程之Python編寫TCP協(xié)議程序的步驟
這篇文章主要介紹了Python網(wǎng)絡編程編寫TCP協(xié)議程序的開發(fā)步驟,通過實例代碼介紹了TCP客戶端程序開發(fā),案例講解多任務版TCP服務端程序開發(fā),需要的朋友可以參考下2022-11-11
Python中dumps與dump及l(fā)oads與load的區(qū)別
這篇文章主要介紹了Python中dumps與dump、loads與load的區(qū)別,json模塊提供了一種很簡單的方式來編碼和解碼JSON數(shù)據(jù)。其中兩個主要的函數(shù)是json.dumps()和json.loads(),需要的朋友可以參考下2022-04-04

