嵌套关系Django的1.11串行嵌套关系没有工作,因为它sholuld是
串行:
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": "[email protected]",
"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'
]
这里我的职务序列化程序的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"
}
有没有什么解决办法吗?我搜索,但没有找到任何。
您好, 我把这个上模型.. 'category = models.ForeignKey(Category,related_name ='cat_posts',default = 1) tags = models.ManyToManyField(Tags,related_name ='rel_posts',help_text =“为该评论选择标签” )' for categor y和标签。我应该将类别'related_name'更改为'posts'吗?但为什么?不应该比'posts'不能运作? 我只是没有得到它。你能描述一下吗?谢谢。 – Hemel
@文档中的hemel:''''''''''''''''''''''''''''''''''''''一般情况下,您需要确保您已经在关系上设置了适当的related_name参数,您可以将其用作字段名称.'因此,如果您有相关名称,则还需要使用该名称在串行器中。或者您可以尝试在'posts'字段上设置源代码:'posts = PostDetailSerializer(many = True,read_only = True,source ='cat_posts')'。 – neverwalkaloner
“post_set”将如何工作而不是“posts”?如果在你给出的例子中'related_name'的模型是'posts'? – Hemel