I have developed an API using django-rest-framework. I am using ModelSerializer to return data of a 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 an API response any value which is not present should not be sent in the response. When the title
is null
I want the response to be:
{ "meta": { "name": "XYZ" } }
I found this solution to be the simplest.
from collections import OrderedDict from rest_framework import serializers class NonNullModelSerializer(serializers.ModelSerializer): def to_representation(self, instance): result = super(NonNullModelSerializer, self).to_representation(instance) return OrderedDict([(key, result[key]) for key in result if result[key] is not None])
I faced a similar problem and solved it as follows:
from operator import itemgetter class MetaTagsSerializer(serializers.ModelSerializer): class Meta: model = MetaTags def to_representation(self, instance): ret = super().to_representation(instance) # Here we filter the null values and creates a new dictionary # We use OrderedDict like in original method ret = OrderedDict(filter(itemgetter(1), ret.items())) return ret
Or if you want to filter only empty fields you can replace the itemgetter(1)
by the following:
lambda x: x[1] is not None
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With