from rest_framework.decorators import api_view from rest_framework.response import Response #reverse函數返回徹底合格的URLs from rest_framework.reverse import reverse @api_view(['GET']) def api_root(request,format=None): return Response({ 'users':reverse('user-list',request=request,format=format), 'myLesson':reverse('myLesson-list',request=request,format=format) })
from rest_framework import renderers class MyLessonHighlight(generics.GenericAPIView): queryset = MyLesson.objects.all() serializer_class = MyLessonSerializer renderer_classes = (renderers.StaticHTMLRenderer,) def get(self,request,*args,**kwargs): myLesson = self.get_object() return Response(myLesson.highlighted)
url(r'^$', views.api_root), url(r'^myLesson/(?P<pk>[0-9]+)/highlight/$', views.MyLessonHighlight.as_view()),
from rest_framework import serializers from myLesson.models import MyLesson from django.contrib.auth.models import User class MyLessonSerializer(serializers.HyperlinkedModelSerializer): owner = serializers.ReadOnlyField(source='owner.username') url = serializers.HyperlinkedIdentityField(view_name="myLesson-detail") highlight = serializers.HyperlinkedIdentityField(view_name='myLesson-highlight',format='html') class Meta: model = MyLesson fields = ('url','id','highlight','owner','title','code','linenos','language','style') class UserSerializer(serializers.HyperlinkedModelSerializer): # myLesson = serializers.PrimaryKeyRelatedField(many=True,queryset=MyLesson.objects.all()) myLesson = serializers.HyperlinkedRelatedField(many=True,view_name='myLesson-detail',read_only=True) class Meta: model = User fields = ('url','id','username','myLesson')
from django.conf.urls import url,include from myLesson import views from rest_framework.urlpatterns import format_suffix_patterns urlpatterns = [ url(r'^$',views.api_root), url(r'^users/$',views.UserList.as_view(),name='user-list'), url(r'^users/(?P<pk>[0-9]+)/$',views.UserDetail.as_view(),name='user-detail'), url(r'^myLesson/$',views.MyLessonList.as_view(),name='myLesson-list'), url(r'^myLesson/(?P<pk>[0-9]+)/$',views.MyLessonDetail.as_view(),name='myLesson-detail'), url(r'^myLesson/(?P<pk>[0-9]+)/highlight/$',views.MyLessonHighlight.as_view(),name='myLesson-highlight'),] urlpatterns = format_suffix_patterns(urlpatterns)
# myTest/settings.py REST_FRAMEWORK = { 'PAGINATE_BY': 10 }
【6】修改bug,按照官網文檔的代碼寫完運行調試,有bug,報錯html
Could not resolve URL for hyperlinked relationship using view name "mylesson-detail". You may have failed to include the related model in your API, or incorrectly configured the lookup_field attribute on this field.數據庫
修改問題參考連接:http://stackoverflow.com/questions/20550598/django-rest-framework-could-not-resolve-url-for-hyperlinked-relationship-usingdjango
解決辦法:在MyLessonSerializer中添加url說明:api
url = serializers.HyperlinkedIdentityField(view_name="myLesson-detail")less