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": "Bobby@gmail.com",
"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": "Bobby@gmail.com",
"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.
You could make a Custom serializer as Rajesh pointed out. Note that this serializer is read-only.
You would then need to remove the posts field from the UserSerializer so that the posts aren't nested inside that one also.