详解从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
翻译自:https://stackoverflow.com/questions/27015931/remove-null-fields-from-django-rest-framework-response
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。
- Django的HttpRequest和HttpResponse对象详解
- Django使用HttpResponse返回图片并显示的方法
- Django使用httpresponse返回用户头像实例代码
- django rest framework之请求与响应(详解)
- django从请求到响应的过程深入讲解
- 从请求到响应过程中django都做了哪些处理
- Django框架的使用教程路由请求响应的方法
- 在Python的Django框架中用流响应生成CSV文件的教程
- Django 中使用流响应处理视频的方法
- Django 响应数据response的返回源码详解
- django创建简单的页面响应实例教程
- Django框架HttpResponse对象用法实例分析
相关文章
Biblibili视频投稿接口分析并以Python实现自动投稿功能
这篇文章主要介绍了Biblibili视频投稿接口分析并以Python实现自动投稿功能,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下2021-02-02Python matplotlib绘图时指定图像大小及放大图像详解
Matplotlib是一个面向对象的绘图库,我们绘制的图像中,每条曲线,每个边框等等都对应一个对象,下面这篇文章主要给大家介绍了关于Python matplotlib绘图时指定图像大小及放大图像的相关资料,需要的朋友可以参考下2022-05-05Tensorflow卷积实现原理+手写python代码实现卷积教程
这篇文章主要介绍了Tensorflow卷积实现原理+手写python代码实现卷积教程,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧2020-05-05Python 列表排序方法reverse、sort、sorted详解
本文给大家介绍的是Python中列表排序方法中的reverse、sort、sorted操作方法,以及他们直接的区别介绍,有需要的小伙伴可以参考下。2016-01-01使用 Python 合并多个格式一致的 Excel 文件(推荐)
这篇文章主要介绍了使用 Python 合并多个格式一致的 Excel 文件,本文给大家介绍的非常详细,具有一定的参考借鉴价值,需要的朋友可以参考下2019-12-12
最新评论