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

依然范特西╮ 提交于 2020-01-07 06:47:33

问题


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:


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.



来源:https://stackoverflow.com/questions/42150996/django-nest-the-object-im-serializing-into-the-serializer

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!