Can I save data in django in a reverse foreign key relation.
Suppose I have models,
class Author(models.Model):
author_id = models.SlugField(default=None, blank=True)
author_name = models.CharField(max_length=200)
class Article(models.Model):
author = models.ForeignKey(Author, on_delete=models.CASCADE)
article_title = models.CharField(max_length=200)
content = models.CharField(max_length=200)
Suppose I want to save all articles with their author data what type of serializer should I use. I am receiving data in this form:
article_data =[
{
"article_title":"one title",
"content":"content",
"author":{
"author_id":"2",
"author_name":"some name",
}
},
{
"article_title":"one title",
"content":"content",
"author":{
"author_id":"2",
"author_name":"some name",
}
}
]
How should I write my serializer to save such data. I dont want to write my logic views file. I dont want to loop over all my articles and then save article and author separately using two serialzer. What I want is calling a single serializer and passing the entire list to it:
saveArticleAndAuthor(article_data, many=True)
the serialzier must save author data to author table and rest of the data to article table.