您好,登錄后才能下訂單哦!
這篇文章主要為大家展示了“如何從Django Rest Framework響應(yīng)中刪除空字段”,內(nèi)容簡而易懂,條理清晰,希望能夠幫助大家解決疑惑,下面讓小編帶領(lǐng)大家一起研究并學(xué)習(xí)一下“如何從Django Rest Framework響應(yīng)中刪除空字段”這篇文章吧。
我使用django-rest-framework開發(fā)了一個(gè)API.
我正在使用ModelSerializer返回模型的數(shù)據(jù).
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
響應(yīng)
{ "meta": { "title": null, "name": "XYZ" } }
理想情況下,在API響應(yīng)中,不應(yīng)在響應(yīng)中發(fā)送任何不存在的值.
當(dāng)標(biāo)題為null時(shí),我希望響應(yīng)為:
{ "meta": { "name": "XYZ" } }
您可以嘗試覆蓋to_native函數(shù):
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復(fù)制了基本的to_native函數(shù),并添加了一個(gè)值的檢查.
更新:
至于DRF 3.0,to_native()被重命名為to_representation(),其實(shí)現(xiàn)稍有改變.這是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響應(yīng)中刪除空字段”這篇文章的所有內(nèi)容,感謝各位的閱讀!相信大家都有了一定的了解,希望分享的內(nèi)容對(duì)大家有所幫助,如果還想學(xué)習(xí)更多知識(shí),歡迎關(guān)注億速云行業(yè)資訊頻道!
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請(qǐng)聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。