如何从DjangoRestFramework响应中删除空字段-创新互联
这篇文章主要为大家展示了“如何从Django Rest Framework响应中删除空字段”,内容简而易懂,条理清晰,希望能够帮助大家解决疑惑,下面让小编带领大家一起研究并学习一下“如何从Django Rest Framework响应中删除空字段”这篇文章吧。
公司专注于为企业提供网站制作、成都网站设计、微信公众号开发、成都商城网站开发,微信小程序,软件定制设计等一站式互联网企业服务。凭借多年丰富的经验,我们会仔细了解各客户的需求而做出多方面的分析、设计、整合,为客户设计出具风格及创意性的商业解决方案,创新互联更提供一系列网站制作和网站推广的服务。我使用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
以上是“如何从Django Rest Framework响应中删除空字段”这篇文章的所有内容,感谢各位的阅读!相信大家都有了一定的了解,希望分享的内容对大家有所帮助,如果还想学习更多知识,欢迎关注创新互联行业资讯频道!
网站标题:如何从DjangoRestFramework响应中删除空字段-创新互联
当前路径:http://scjbc.cn/article/ijhoi.html