I have two models like this:
class Category(models.Model):
title = models.CharField(max_length=256)
class Post(models.Model):
title = models.CharField(max_length=256, default=None, blank=True)
content = models.TextField()
created_at = models.DateTimeField(auto_now=True)
category_id = models.ForeignKey(Category, on_delete=models.CASCADE)
And have two serializer:
class CategorySerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Category
fields = ['id', 'title']
class PostSerializer(serializers.ModelSerializer):
class Meta:
model = Post
fields = ['id', 'title', 'content', 'created_at', 'category_id']
How to prepare response like this:
"data": [
{
"id": 1,
"title": "Hello1",
"content": "Hello content1",
"created_at": "2021-09-25T07:57:23.532416Z",
"category_id": 11,
"category": {"id":11 , "title":"Category1"}
},
{
"id": 2,
"title": "Hello2",
"content": "Hello content2",
"created_at": "2021-09-25T08:08:37.984310Z",
"category_id": 12,
"category": {"id":12 , "title":"Category2"}
}
]
CodePudding user response:
You add a Category
sub-serializer:
class PostSerializer(serializers.ModelSerializer):
category = CategorySerializer()
class Meta:
model = Post
fields = ['id', 'title', 'content', 'created_at', 'category', 'category_id']