Reference Information. I have an article model that stores some articles, and each article can have multiple images. I need to create an api to create an article and related images, if necessary. But I have no idea how to make images work 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):
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 request
{
"title":"Sample Title",
"content":"Sample Content",
"images":[
"paul.jpg",
"ada.jpg"
]
}
Thanks for the help.
source
share