详解从Django Rest Framework响应中删除空字段

沈亦白
沈亦白
发布时间:2026-10-13| 7人浏览过
原创

本文介绍如何在Django Rest Framework中通过重写序列化器的to_native或to_representation方法,自动过滤API响应中的null和空字符串字段。针对DRF不同版本提供了具体代码示例,帮助开发者生成更简洁的JSON数据。

笔者利用Django Rest Framework构建了应用程序接口。

在数据返回环节,采用了ModelSerializer来序列化模型对象。

模型定义文件

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)

序列化器定义文件

class MetaTagsSerializer(serializers.ModelSerializer):
 class Meta:
  model = MetaTags

接口返回结果

{
 "meta": {
  "title": null,
  "name": "XYZ"
 }
}

从数据规范角度看,理想的API响应应当剔除那些不存在或无意义的字段。

当title字段值为null时,期望的响应格式如下所示:

{
 "meta": {
  "name": "XYZ"
 }
}

一种可行的方案是重写to_native方法:

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函数进行修改,并增加了针对字段值的判断逻辑。

补充说明:

针对DRF 3.0版本,原to_native()方法已更名为to_representation(),且内部实现有所调整。以下是适用于DRF 3.0的代码,该代码能够忽略null值和空字符串值:

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

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持本站。

免责声明:本文内容仅供参考,不代表本站观点。转载或引用请注明出处。

Python 相关产品和应用

全部下载
Selenium

Selenium

4.51.0 · Windows

用于浏览器自动化和 Web 测试的 Python 工具。

scikit-learn

scikit-learn

1.9.1 · Windows

常用 Python 机器学习算法与模型评估工具库。

Black

Black

26.10.1 · Windows

强调一致性的 Python 自动代码格式化工具。

Ruff

Ruff

0.17.1 · macOS

由 Rust 编写的高速 Python 代码检查和格式化工具。

pytest

pytest

9.1.1 · Windows

简洁而强大的 Python 自动化测试框架。

FastAPI

FastAPI

0.146.0 · Windows

高性能 Python API 框架,支持类型提示和自动接口文档。

Flask

Flask

3.1.3 · Windows

轻量灵活的 Python Web 应用框架。

Django

Django

6.1.2 · Windows

成熟的 Python Web 框架,适合构建内容站点和业务系统。

Spyder

Spyder

6.1.7 · Windows

面向科学计算与数据分析的 Python 集成开发环境。

SciPy

SciPy

1.18.1 · Windows

面向科学、工程和技术计算的 Python 算法库。