如何在另一个序列化程序中添加序列化程序?这就是我的意思:
我有一个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,完全忽略了帖子。
答案 0 :(得分:2)
尝试使用SerializerMethodField
从PostsSerializer
获取帖子,并在“帖子”字段中手动将其添加到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