Remove null fields from Django Rest Framework response
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