django-rest-framework學習之Relationships & Hyperlinked APIs--2017年4月17日至18日

 
Relationships & Hyperlinked APIs
 
參考連接:
 
目前咱們API中的關係用primary keys展現,這部分咱們會經過hyperlinking提升咱們API的內聚性和擴展性
 
【1】給API的根節點傳建一個端點
在views.py中添加:
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)
    })
 
【2】爲highlighted建立一個端點
和其餘API不一樣的是,咱們不用JSON格式,而是用HTML展現,Rest framework提供了兩種風格的HTML Render,一個是使用模板,另外一個用pre_rendererd,這裏咱們使用第二個
由於咱們要返回的不是一個類,而是一個屬性,因此沒有咱們可以是用的具體的generic view,因此咱們用generics.GenericAPIView並本身建立get方法
 
在views.py中添加:
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)
 
在mylesson中urls.py添加:
url(r'^$', views.api_root),
url(r'^myLesson/(?P<pk>[0-9]+)/highlight/$', views.MyLessonHighlight.as_view()),
 
【3】給API添加超連接
有不少方式能夠展現實體間的關係:primary keys, hyperlinking, unique identifying slug field, default string, 或者使兩個類繼承自一個母體
REST framework 提供了上述全部風格,在此case中咱們使用hyperlinked,使用HyperlinkedModelSerializer
HyperlinkedModelSerializer 和 ModelSerializer 的區別:沒有id,多了url,用HyperlinkedRelatedField代替PrimaryKeyRelatedField
 
所以咱們重寫serializers.py
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')
 
【4】確認URL patterns已經被命名
 
修改myLesson/urls.py:
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)
 
【5】添加分頁
若是數據庫中的數據達到必定程度, 那麼用戶使用api時可能會返回大量數據, 所以, 咱們最好使用分頁功能。
咱們可使用django-rest-framework自帶的設置選項, 使list自動使用分頁:
# 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

相關文章
相關標籤/搜索