python - Remove null fields from Django Rest Framework response -
i have developed api using django-rest-framework. using modelserializer return data of model.
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
response
{ "meta": { "title": null, "name": "xyz" } }
ideally in api response value not present should not sent in response. when title
null
want response be:
{ "meta": { "name": "xyz" } }
you try overriding to_native function:
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() field_name, field in self.fields.items(): if field.read_only , obj 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 none not serialized. if value 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
i copied base to_native function serializers.baseserializer
, added check value.
Comments
Post a Comment