gpt4 book ai didi

python - 如何使用 Django Rest Framework 将 url 字段添加到序列化程序

转载 作者:太空狗 更新时间:2023-10-30 02:28:30 24 4
gpt4 key购买 nike

我正在学习 Django Rest Framework - Tutorial 3 Class based views 上的教程.

如何将 url 字段(指向当前片段)添加到序列化程序?

序列化器.py

from rest_framework import serializers
from snippets.models import Snippet, LANGUAGE_CHOICES, STYLE_CHOICES
from django.core.urlresolvers import reverse

class SnippetSerializer(serializers.ModelSerializer):

class Meta:
model = Snippet
fields = ('id', 'title', 'code', 'linenos', 'language', 'style')

urls.py

urlpatterns = [
url(r'^snippets/$', views.SnippetList.as_view()),
url(r'^snippets/(?P<pk>[0-9]+)/$', views.SnippetDetail.as_view()),
]

实际输出

[  
{
"id":1,
"title":"",
"code":"foo = \"bar\"\n",
"linenos":false,
"language":"python",
"style":"friendly"
}
]

期望的输出

[  
{
"id":1,
"url":"http://192.168.28.131:8000/snippets/1/",
"title":"",
"code":"foo = \"bar\"\n",
"linenos":false,
"language":"python",
"style":"friendly"
},

]

最佳答案

你必须使用 HyperlinkedModelSerializer 序列化器和 HyperlinkedIdentityField 字段

来自 Django Rest Framework documentation

The HyperlinkedModelSerializer class is similar to the ModelSerializer class except that it uses hyperlinks to represent relationships, rather than primary keys. The url field will be represented using a HyperlinkedIdentityField serializer field, and any relationships on the model will be represented using a HyperlinkedRelatedField serializer field.

例如(你的情况):

class SnippetSerializer(serializers.HyperlinkedModelSerializer):
url = serializers.HyperlinkedIdentityField(view_name='snippet-detail', read_only=True)

class Meta:
model = Snippet
fields = ('id', 'url', 'title', 'code', 'linenos', 'language', 'style')

当然,view_name 值必须与在 urls.py(或其他地方没有)中声明的 url 名称相匹配,用于获取有关片段的所有信息。

例如:

# urls.py
urlpatterns = [
url(r'^snippets/(?P<pk>[0-9]+)$', views.SnippetDetail.as_view(), name='snippet-detail'),
]

关于python - 如何使用 Django Rest Framework 将 url 字段添加到序列化程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36697088/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com