I am trying to exclude the fields of the nested-Serializer. How do I go about doing it?
For example, for a serializer
class UserDetailSerializer(serializers.ModelSerializer):
user = UserSerializer() # want to exclude fields in this serializer
other = OtherSerializer()
class Meta:
model = User
It should work like
serialized = UserDetailSerializer(user_detail, exclude=['fields'])
And the exclude values should be passed onto the other serializers, that is to both UserSerializer and OtherSerializer.
I've a modified version of DynamicFieldsModelSerializer in the drf documentation but it only works for the class that inherits from it.
class DynamicFieldsModelSerializer(serializers.ModelSerializer):
"""
A ModelSerializer that takes an additional `fields` argument that
controls which fields should be displayed.
"""
def __init__(self, *args, **kwargs):
# Don't pass the 'fields' arg up to the superclass
fields = kwargs.pop('fields', None)
exclude = kwargs.pop('exclude', None)
# Instantiate the superclass normally
super().__init__(*args, **kwargs)
if fields is not None:
# Drop any fields that are not specified in the `fields` argument.
allowed = set(fields)
existing = set(self.fields.keys())
for field_name in existing - allowed:
self.fields.pop(field_name)
elif exclude is not None:
# drop fields that are specified in the 'exclude' argument
for field_name in set(exclude):
self.fields.pop(field_name)