嵌套关系 django 1.11
序列化器:
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',
]
响应:
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": "hello@ihemel.net",
"first_name": "Hasibul Amin",
"last_name": "Hemel"
}
}
这是检索数据的良好嵌套关系。
但在我的类别中再次详细说明下面的 api 序列化程序:
class CategoryDetailSerializer(ModelSerializer):
url = category_detail_url
posts = PostDetailSerializer(many=True, read_only=True)
class Meta:
model = Category
fields = [
'id',
'url',
'name',
'posts'
]
这里我的post serializer 不在api 中输出任何数据。我不知道。没有错误或错误,只是值没有出现。
分类详情api响应:
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"
}
有什么解决办法吗?我搜索了但没有找到。
最佳答案
由于您在 CategoryDetailSerializer
中使用字段名 posts
,因此您需要将 related_name=posts
设置为 Post
中的类别关系> 型号:
class Post(Model):
category = ForeignKey(Category, related_name='posts')
或者您可以在 CategoryDetailSerializer
中使用默认关系名称 post_set
:
class CategoryDetailSerializer(ModelSerializer):
url = category_detail_url
post_set = PostDetailSerializer(many=True, read_only=True)
class Meta:
model = Category
fields = [
'id',
'url',
'name',
'post_set'
]
查看详情 here .
您也可以尝试使用模型中的 related_name 在序列化程序字段上指定源:
posts = PostDetailSerializer(many=True, read_only=True, source='cat_posts')
关于django - 序列化程序嵌套关系无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45987763/