详解从Django Rest Framework响应中删除空字段
我使用django-rest-framework开发了一个API.
我正在使用ModelSerializer返回模型的数据.
models.py
classMetaTags(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
classMetaTagsSerializer(serializers.ModelSerializer): classMeta: model=MetaTags
响应
{ "meta":{ "title":null, "name":"XYZ" } }
理想情况下,在API响应中,不应在响应中发送任何不存在的值.
当标题为null时,我希望响应为:
{ "meta":{ "name":"XYZ" } }
您可以尝试覆盖to_native函数:
classMetaTagsSerializer(serializers.ModelSerializer): classMeta: model=MetaTags defto_native(self,obj): """ Serializeobjects->primitives. """ ret=self._dict_class() ret.fields=self._dict_class() forfield_name,fieldinself.fields.items(): iffield.read_onlyandobjisNone: continue field.initialize(parent=self,field_name=field_name) key=self.get_field_key(field_name) value=field.field_to_native(obj,field_name) #ContinueifvalueisNonesothatitdoesnotgetserialized. ifvalueisNone: continue method=getattr(self,'transform_%s'%field_name,None) ifcallable(method): value=method(obj,value) ifnotgetattr(field,'write_only',False): ret[key]=value ret.fields[key]=self.augment_field(field,field_name,key,value) returnret
我基本上从serializers.BaseSerializer复制了基本的to_native函数,并添加了一个值的检查.
更新:
至于DRF3.0,to_native()被重命名为to_representation(),其实现稍有改变.这是DRF3.0的代码,它忽略空值和空字符串值:
defto_representation(self,instance): """ Objectinstance->Dictofprimitivedatatypes. """ ret=OrderedDict() fields=self._readable_fields forfieldinfields: try: attribute=field.get_attribute(instance) exceptSkipField: continue #KEYISHERE: ifattributein[None,'']: continue #Weskip`to_representation`for`None`valuessothatfieldsdo #nothavetoexplicitlydealwiththatcase. # #Forrelatedfieldswith`use_pk_only_optimization`weneedto #resolvethepkvalue. check_for_none=attribute.pkifisinstance(attribute,PKOnlyObject)elseattribute ifcheck_for_noneisNone: ret[field.field_name]=None else: ret[field.field_name]=field.to_representation(attribute) returnret
翻译自:https://stackoverflow.com/questions/27015931/remove-null-fields-from-django-rest-framework-response
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。