详解从Django Rest Framework响应中删除空字段
程序员文章站
2023-11-04 20:21:22
我使用django-rest-framework开发了一个api.
我正在使用modelserializer返回模型的数据.
models.py
class...
我使用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
翻译自:
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。