详解从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(PyS60)实现简单语音整点报时

本文实例为大家分享了python语音整点报时的具体代码,供大家参考,具体内容如下 主要的技术特殊点在于PyS60的定时器最多只能定2147秒。在手机上直接写的。 import e...

python实现闹钟定时播放音乐功能

自己写的闹钟,只可以播放wav格式的音频,供大家参考,具体内容如下 Python代码: import time import sys soundFile = 'sound....

对python中类的继承与方法重写介绍

对python中类的继承与方法重写介绍

1.单继承 父类也叫基类 子类也叫派生类 如下所示,继承的关系: 继承的书写格式: class 子类(父类): 方法 实例: class Animal:...

python中ImageTk.PhotoImage()不显示图片却不报错问题解决

python中ImageTk.PhotoImage()不显示图片却不报错问题解决

发现问题 今天在使用ImageTk.photoImage()显示图片时,当把包含该函数放在自定义函数里时,不能正常显示,移到函数为又可正常显示,所以想到可能是变量不是全局性的缘故,改为全...

python去掉 unicode 字符串前面的u方法

有时我们会碰到类似下面这样的 unicode 字符串: u'\xe4\xbd\xa0\xe5\xa5\xbd' 这明显不是一个正确的 unicode 字符串,可能是在哪个地方转码转...