Nested relationships django 1.11
serializer:
class PostDetailSerializer(ModelSerializer):
url = post_detail_url
user = UserSerializer(read_only=True)
image = SerializerMethodField()
html = SerializerMethodField()
tags = TagSerializer(many=True)
category = CategorySerializer()
source = SourceSerializer()
class Meta:
model = Post
fields = [
'id',
'url',
'title',
'image',
'slug',
'content',
'source',
'source_link',
'category',
'tags',
'html',
'publish',
'timestamp',
'user',
]
Response:
HTTP 200 OK
Allow: GET, HEAD, OPTIONS
Content-Type: application/json
Vary: Accept
{
"id": 3,
"url": "http://127.0.0.1:8000/api/v1/posts/new-postas/",
"title": "New Postaas",
"image": null,
"slug": "new-postas",
"content": "asssaasssasa",
"source": {
"id": 1,
"name": "prothom alo",
"slug": "prothom-alo"
},
"source_link": "http://prothom-alo.com/",
"category": {
"id": 2,
"url": "http://127.0.0.1:8000/api/v1/posts/category/news/",
"name": "news"
},
"tags": [
{
"id": 1,
"name": "tech",
"slug": "tech"
}
],
"html": "<p>asssaasssasa</p>\n",
"publish": "2017-08-31",
"timestamp": "2017-08-31T12:28:28.686538Z",
"user": {
"id": "ac32460f-fb7e-4755-9f7e-7c13085ee92b",
"email": "[email protected]",
"first_name": "Hasibul Amin",
"last_name": "Hemel"
}
}
This is fine nested relation retrieving the data.
But again in my category details api serializer below:
class CategoryDetailSerializer(ModelSerializer):
url = category_detail_url
posts = PostDetailSerializer(many=True, read_only=True)
class Meta:
model = Category
fields = [
'id',
'url',
'name',
'posts'
]
Here my post serializer does not output any data in the api. I don't know. there no bug or error, just the value is not coming.
The category details api response:
HTTP 200 OK
Allow: GET, HEAD, OPTIONS
Content-Type: application/json
Vary: Accept
{
"id": 2,
"url": "http://127.0.0.1:8000/api/v1/posts/category/news/",
"name": "news"
}
Is there any solution? i searched but not found any.
Since you are using fieldname
posts
inCategoryDetailSerializer
you need to setrelated_name=posts
to category relation insidePost
model:Or you can use default relation name
post_set
inCategoryDetailSerializer
:See details here.
Also you can try to specify source on the serializer field using related_name from model: