内容简介:翻译自:https://stackoverflow.com/questions/27015931/remove-null-fields-from-django-rest-framework-response
我使用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
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网
猜你喜欢:- springboot~DTO字符字段与日期字段的转换问题
- Protocol Buffers 学习(2):字段类型和其他语言字段类型之间的映射
- Protocol Buffers 学习(2):字段类型和其他语言字段类型之间的映射
- PHPRAP 2.0.2 发布,接口和字段数据分离,字段使用单独数据表
- 如何正确新增字段
- HTTP缓存字段总结
本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。
图解物联网
[ 日] NTT DATA集团、河村雅人、大塚纮史、小林佑辅、小山武士、宫崎智也、石黑佑树、小岛康平 / 丁 灵 / 人民邮电出版社 / 2017-4 / 59.00元
本书图例丰富,从设备、传感器及传输协议等构成IoT的技术要素讲起,逐步深入讲解如何灵活运用IoT。内容包括用于实现IoT的架构、传感器的种类及能从传感器获取的信息等,并介绍了传感设备原型设计必需的Arduino等平台及这些平台的选择方法,连接传感器的电路,传感器的数据分析,乃至IoT跟智能手机/可穿戴设备的联动等。此外,本书以作者们开发的IoT系统为例,讲述了硬件设置、无线通信及网络安全等运用Io......一起来看看 《图解物联网》 这本书的介绍吧!