'Reverse foreign key relation in django serializers
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.
Solution 1:[1]
you need two classes in serializer.py
class Author_serializer(serializers.ModelSerializer):
class Meta:
model = Article
fields = ["author_id", "author_name"]
and and second must be under Author_serializer
class saveArticleAndAuthor_serializer(serializers.ModelSerializer):
class Meta:
model = Article
fields = ["author", "article_title", "content"]
author = Author_serializer()
in views.py you use only saveArticleAndAuthor_serializer and it will serialize Author_serializer as "second level depth"
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | oruchkin |
