rocky raccoon
rocky raccoon

Reputation: 544

Django: adding two serializers together?

How is it possible to add a serializer within another serializer? Here's what I mean:

I have a UserProfile model as such:

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

I have posts which are from the user:

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

I want to serialize my UserProfile with the user and photo, as well as the posts from that user. Here's the result I'm aiming for:

{ "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],"
}

In my views.py I first gather the posts which come from that User:

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?

Here is my PostsSerializer.py:

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

Here is my UserSerializer.py:

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

I've tried serializing the user profile, and because I added a serializer variable inside my UserProfileSerializer, I assumed it would add the field of posts automatically. It just shows the User Profiler serialized, ignoring the posts altogether.

Upvotes: 2

Views: 2235

Answers (1)

Steven Moseley
Steven Moseley

Reputation: 16355

Try using a SerializerMethodField to get the posts from the PostsSerializer, and manually add them in a "posts" field to your UserProfileSerializer output, e.g.

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

Upvotes: 2

Related Questions