Created
June 3, 2019 04:20
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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