英文:
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
.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论