如何为一对多(外键)关系创建序列化程序?

huangapple go评论73阅读模式
英文:

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

问题

我的模型是:

class Posts(models.Model):
    user = models.ForeignKey(User, related_name='user_posts', on_delete=models.CASCADE, null=True, blank=True)
    ###其他字段

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)
英文:

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

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)

答案1

得分: 1

你可以为你的PostsMedia模型创建一个序列化器,以允许上传多个图片并保存它们的URL,如下所示:

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() 方法被用来从验证过的数据中提取post_media数据。

注意:在Django中,模型不需要添加s作为后缀,因为它默认包含在内。所以最好将Posts改为Post

英文:

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 [tag:django] don't require s to be added as suffix, since it is included by default. So it is better to change Posts to Post.

huangapple
  • 本文由 发表于 2023年3月1日 14:00:37
  • 转载请务必保留本文链接:https://go.coder-hub.com/75600056.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定