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

yipeiwu_com5年前Python基础

我使用django-rest-framework开发了一个API.

我正在使用ModelSerializer返回模型的数据.

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响应中,不应在响应中发送任何不存在的值.

当标题为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的代码,它忽略空值和空字符串值:

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设计】。

相关文章

python编写计算器功能

python编写计算器功能

本文实现用python编写一个带界面的计算器小程序,当然这个计算器功能很简单,只能进行一些简单的数学运算,很适合初学者,希望能给大家带来一些启发 实验前提 因为是带图形界面的,所以...

python random从集合中随机选择元素的方法

如下所示: list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] slice = random.sample(list, 5) #从list中随机获取5个元...

Python 中开发pattern的string模板(template) 实例详解

定制pattern的string模板(template) 详解 string.Template的pattern是一个正则表达式, 可以通过覆盖pattern属性, 定义新的正则表达式....

记录Python脚本的运行日志的方法

一、logging模块 Python中有一个模块logging,可以直接记录日志 # 日志级别 # CRITICAL 50 # ERROR 40 # WARNING 30 #...

Python解决N阶台阶走法问题的方法分析

本文实例讲述了Python解决N阶台阶走法问题的方法。分享给大家供大家参考,具体如下: 题目:一栋楼有N阶楼梯,兔子每次可以跳1、2或3阶,问一共有多少种走法? Afanty的分析: 遇...