嵌套關係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