[Answered ]-How do I create a serializer for one to many (Foreign key) relationship?

1👍

You can create a serializer for your PostsMedia model to allow for uploading multiple images and saving their URLs so:

class PostsMediaSerializer(serializers.ModelSerializer):
    class Meta:
        model = PostsMedia
        fields = ('id', 'media')


class PostsSerializer(serializers.ModelSerializer):
    post_media = PostsMediaSerializer(many=True, required=False)

    class Meta:
        model = Posts
        fields = ('id', 'user', 'post_media', '__all__')

    def create(self, validated_data):
        post_media_data = validated_data.pop('post_media', [])
        post = super().create(validated_data)

        for one_media_data in post_media_data:
            PostsMedia.objects.create(post=post, **one_media_data)

        return post

create() method has been used to extract the post_media data from the validated data.

Note: Models in don’t require s to be added as suffix, since it is included by default. So it is better to change Posts to Post.

Leave a comment