rocky raccoon
rocky raccoon

Reputation: 544

Django: nest the object I'm serializing into the serializer?

I'm looking to nest the object I'm serializing. Here's what I mean:

My current UserSerializer:

class UserSerializer(serializers.ModelSerializer):
    posts = serializers.SerializerMethodField()
    class Meta:
        model = User
        fields = ('__all__')
    def get_posts(self, user):
        posts = Posts.objects.get_posts_for_user(user=user)
        return PostsSerializer(posts, many=True, context=self.context)

Here's my PostsSerializer:

class PostsSerializer(serializers.ModelSerializer):
    class Meta:
        model = Posts
        fields = ('__all__')

Here's what's how it's being serialized:

{ "name": "Bobby Busche", 
  "email": "[email protected]",
  "posts": [ {"from_user": "me", "message": "Hello World"},
             {"from_user": "me", "message": "Bye bye"} ],
  "username": "ilovemymomma"
}

But I want the user to be grouped inside the key "user" like this:

{ "user": { "name": "Bobby Busche", 
             "email": "[email protected]",
             "username": "ilovemymomma" }
  "posts": [ {"from_user": "me", "message": "Hello World"},
             {"from_user": "me", "message": "Bye bye"} ]

}

I need a bit of guidance on what's the best approach to execute for this.

Upvotes: 0

Views: 190

Answers (1)

Ruben Schmidt
Ruben Schmidt

Reputation: 141

You could make a Custom serializer as Rajesh pointed out. Note that this serializer is read-only.

class UserPostsSerializer(serializers.BaseSerializer):

    def to_representation(self, instance):
        posts = Posts.objects.get_posts_for_user(user=instance)
        return {
            'user': UserSerializer(instance).data,
            'posts': PostSerialzer(posts, many=True).data
        }

You would then need to remove the posts field from the UserSerializer so that the posts aren't nested inside that one also.

Upvotes: 3

Related Questions