Home > Software design >  Hey is it possible to call one serializer class insider another in drf? Without having any foreign k
Hey is it possible to call one serializer class insider another in drf? Without having any foreign k

Time:11-21

class AuthorSerializer(ModelSerializer):
    class Meta:
            model =  Author
            fields = "__all__"

class BookSerializer(ModelSerializer):
      class Meta:
            model =  Book
            fields = "__all__"

I want to get data of AuthorSerializer in BookSerializer. Is it Possible?

CodePudding user response:

You can use serailizerMethodField:

class BookSerializer(ModelSerializer):
      author = serializers.SerializerMethodField()

      def get_author(self, obj):
           """ code to perform query """
           author = Author.objects.all()
           return AuthorSerializer(author, many=True).data

      class Meta:
            model =  Book
            fields = "__all__"

The return statement inside get_author function explained:

Returning the author as such returns the query set (thats not the way of serializer), so we pass the data in to AuthorSerializer to make it JSON object. The first argument passing (ie. author) is the query set, and secondly many=True is to say that we are passing multiple objects (in the query set). Lastly .data returns the data serialized.

  • Related