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

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

本文介绍如何在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 相关产品和应用

全部下载

专题列表