Django: nest the object I'm serializing into t

2019-09-17 09:12发布

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.

1条回答
Rolldiameter
2楼-- · 2019-09-17 10:15

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.

查看更多
登录 后发表回答