Django:一起添加两个序列化程序?

Django: adding two serializers together?

如何在另一个序列化器中添加一个序列化器?这就是我的意思:

我有一个 UserProfile 模型:

class UserProfile(models.Model):
    user = models.OneToOneField(User)
    photo =  models.URLField(max_length=128)

我有来自以下用户的帖子:

class Posts(models.Model):
    # ... post fields

我想用用户和照片以及该用户的帖子序列化我的 UserProfile。这是我想要的结果:

{ "user": <User fields serialized>, 
  "photo": "www.example.com/path/to/file", 
  "posts": "[{"from_user": "me", "message": "post message} , 
             {"from_user": "me", "message": "post message2"}, ... etc],"
}

在我的 views.py 中,我首先收集了来自该用户的帖子:

user = User.objects.get(pk=1)
user_profile = UserProfile.objects.get(user=user)
user_profile_serializer = UserProfileSerializer(user_profile)

posts = Posts.objects.get_posts_from_user(user)
post_serializer = PostsSerializer(posts, many=True)
# somehow append my post_serializer into my user_profile_serializer?

这是我的 PostsSerializer.py:

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

这是我的 UserSerializer.py:

class UserProfileSerializer(serializers.ModelSerializer):
    # somehow filter the results depending on User
    posts_serializer = PostsSerializer(many=True)
    class Meta:
        model = UserProfile
        fields = ('__all__')

我已经尝试序列化用户配置文件,因为我在 UserProfileSerializer 中添加了一个序列化程序变量,我假设它会自动添加 posts 字段。它只显示序列化的 User Profiler,完全忽略帖子。

尝试使用 SerializerMethodFieldPostsSerializer 中获取帖子,然后将它们手动添加到 "posts" 字段中到您的 UserProfileSerializer 输出中,例如

class UserProfileSerializer
    ...
    posts = serializers.SerializerMethodField()

    class Meta:
        fields = ("posts", ... other fields, ...}

    def get_posts(self, user):
        posts = Posts.objects.get_posts_from_user(user)
        return PostsSerializer(posts, many=True, context=self.context).data