[英]Django-rest-framework serializer: Create an object with foreign objects at the same time
Background: I have an Article model storing some articles and each article can have multiple images. 背景:我有一个文章模型存储一些文章,每篇文章可以有多个图像。 I need to design an api to create an article and the corresponding images if necessary.
我需要设计一个api来创建一篇文章,并在必要时创建相应的图像。 But I have no ideas of how to make the images can be also created at the same time.
但我不知道如何使图像同时创建。
models.py models.py
class Article(models.Model):
id = models.AutoField(primary_key=True)
title = models.CharField(max_length=50)
content = models.CharField(max_length=255)
def __unicode__(self):
return self.title
class ArticleImage(models.Model):
id = models.AutoField(primary_key=True)
image = models.ImageField(upload_to=get_file_path, blank=True, null=True)
article = models.ForeignKey(Article)
serializers.py serializers.py
class ArticleImageSerializer(serializers.ModelSerializer):
class Meta:
model = ArticleImage
class ArticleSerializer(serializers.ModelSerializer):
#images = ???
class Meta:
model = Article
api.py api.py
class ArticleView(APIView):
def post(self, request, format=None):
try:
serializer = ArticleSerializer(request.data)
if serializer.is_valid():
serializer.save()
return Response({'success': True})
else:
return Response({'success': False})
except:
return Response({'success': False})
Request JSON 请求JSON
{
"title":"Sample Title",
"content":"Sample Content",
"images":[
"paul.jpg",
"ada.jpg"
]
}
Thanks for help. 感谢帮助。
Assuming you're using DRF v3, you can find the answer to your question under the "Writable nested representations" section of the official docs on "Serializers" . 假设您使用的是DRF v3,您可以在“Serializers”官方文档的“可写嵌套表示”部分找到您问题的答案。
Let me know if you need more help. 如果您需要更多帮助,请告诉我。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.