Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

I have to upload multiple images and save their URLs. A number of images can be uploaded but the post will be one, similarly for other posts also. I have created the models but I don’t know how to create the serializer for it.

My models are:

class Posts(models.Model):
    user = models.ForeignKey(User, related_name='user_posts', on_delete=models.CASCADE, null=True, blank=True)
    ###other fields

And

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

class PostsMedia(models.Model):
    post = models.ForeignKey(Posts, related_name='post_media', on_delete=models.CASCADE, null=True, blank=True)
    media = models.URLField(max_length = 500, null=True, blank=True)

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading