Skip to content

Instantly share code, notes, and snippets.

@Joel-hanson
Created June 3, 2019 04:20
Show Gist options
  • Save Joel-hanson/1fd082edeec664e6105973630934677b to your computer and use it in GitHub Desktop.
Save Joel-hanson/1fd082edeec664e6105973630934677b to your computer and use it in GitHub Desktop.
The Nested serializers fields can also be a dynamically modifying fields by using the SerializerMethodField . TheSerializerMethodField can be used to pass the context which contains the requestof the parent serializer, so that we can pass the fields required by us to the nested serializer.
class BookModelSerializer(ModelSerializer):
authors = SerializerMethodField("get_author_serializer")
publisher = SerializerMethodField("get_publisher_serializer")
class Meta:
model = Book
fields = '__all__'
def get_author_serializer(self, obj):
request = self.context.get('request')
serializer_context = {'request': request }
authors = obj.authors.all()
serializer = AuthorModelSerializer(authors, many=True, context=serializer_context)
return serializer.data
def get_publisher_serializer(self, obj):
request = self.context.get('request')
serializer_context = {'request': request }
publisher = obj.publisher
serializer = PublisherModelSerializer(publisher, context=serializer_context)
return serializer.data
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment