我遇到的问题,和这个外国人问题一样,因为app有名字,导致restframework使用HyperlinkedModelSerializer ,里面的url不成功。
他的地址是:https://stackoverflow.com/questions/18231887/model-field-named-url-and-django-rest-framework-url
My serializers.py file:
classSnippetSerializer(serializers.HyperlinkedModelSerializer):
owner=serializers.ReadOnlyField(source='owner.username')
highlight=serializers.HyperlinkedIdentityField(view_name='snip:snippet-highlight', format='html')
#url = serializers.SerializerMethodField('get_snippet_url')
#url=serializers.HyperlinkedIdentityField(view_name='snip:snippet-detail')
classMeta:
model=Snippet
fields=('url','title','code','linenos','language','style','owner','highlight')
# def get_snippet_url(self, obj):
# # generate the url for the key
# url = reverse('snip:snippet-detail')
我的项目根url:
url(r'^snip/', include('snippets.urls', namespace='snip'))
我的app的url:
urlpatterns=format_suffix_patterns([
url(r'^$',api_root),
url(r'^snippets/$',SnippetList.as_view(), name='snippet-list'),
url(r'^snippets/(?P[0-9]+)/$',SnippetDetail.as_view(),name='snippet-detail'),
url(r'^snippets/(?P[0-9]+)/highlight/$',SnippetHighlight.as_view(),name='snippet-highlight'),
url(r'^users/$', UserList.as_view(),name='user-list'),
url(r'^users/(?P[0-9]+)/$', UserDetail.as_view(),name='user-detail'),
])
这样每次,都是告诉我无法找到snippet-detail.
解决办法:
url=serializers.HyperlinkedIdentityField(view_name='snip:snippet-detail')
笔记:
如果我们创建了一个基于超链接的API,我们需要确保每个URL都被命名了。让我们看看那些需要被命名的URL:
1.根URL包含'user-list'和'snippet-list'
2.snippet serializer包含指向'snippet-highlight'的字段
3.user serializer包含指向'snippet-detail'的字段
4. snippet serializers和user serializers 包含'url'字段,这个字段默认指向'{model_name}-detail',这里分别是'snippet-detail'和'user-detail'