Django-rest-framework序列化程序:同时创建一个包含外部对象的对象

背景:我有一个文章模型存储一些文章,每篇文章可以有多个图像.我需要设计一个api来创建一篇文章,并在必要时创建相应的图像.但我不知道如何使图像同时创建.

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

class ArticleImageSerializer(serializers.ModelSerializer):
    class Meta:
        model = ArticleImage

class ArticleSerializer(serializers.ModelSerializer):
    #images = ???
    class Meta:
        model = Article

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})

请求JSON

{  
   "title":"Sample Title",
   "content":"Sample Content",
   "images":[  
      "paul.jpg",
      "ada.jpg"
   ]
}

感谢帮助.

最佳答案 假设您使用的是DRF v3,您可以在“Serializers”官方文档的“可写嵌套表示”部分找到您问题的答案.

如果您需要更多帮助,请告诉我.

点赞