[Answered ]-Is there an easy way to only serialize non-empty fields with Django Rest Framework's ModelSerializer?

1👍

You can override the to_representation method of ModelSerializer:

class NonEmptySerializer(ModelSerializer):
    def to_representation(self, instance):
        ret = super().to_representation(instance)
        non_null_ret = copy.deepcopy(ret)
        for key in ret.keys():
            if not ret[key]:
                non_null_ret.pop(key)
        return non_null_ret

Then inherit from this serialiser when needed:

class OutfitSerializer(NonEmptySerializer):
    class Meta:
        model = Outfit
        fields = '__all__'

Since to_representation is called for both single and list serialisers, it works in both cases.

Leave a comment