Pang
Pang

Reputation: 532

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. But I have no ideas of how to make the images can be also created at the same time.

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

Request JSON

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

Thanks for help.

Upvotes: 4

Views: 1119

Answers (1)

tamakisquare
tamakisquare

Reputation: 17067

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".

Let me know if you need more help.

Upvotes: 2

Related Questions