2016-12-29 161 views

回答

7

APIView是定義REST視圖時通常會覆蓋的最基本的類。您通常定義您的方法,如獲取,放入,刪除和其他檢查(http://www.cdrf.co/3.5/rest_framework.views/APIView.html)。隨着APIView定義您的視圖,你把它添加到你的網址,像這樣:

#in views.py 
class MyAPIView(APIView): 
    ... #here you put your logic check methods you can use 
#in urls.py 
url(r'^posts$', MyAPIView.as_view()), #List of all the posts 

因爲某些事情像獲得/後/ 4,刪除/後/ 4,讓所有的帖子,更新和創造新帖子非常常見,DRF提供Viewsets。

但是,在你知道Viewsets之前,讓我告訴你還有一些泛型類,他們做的事情非常好,但是你需要提供完整的API終點,就像我對MyAPIView視圖做的一樣(再次查看更多信息http://www.cdrf.co/http://www.django-rest-framework.org/)。所以你必須定義你自己的網址路徑。

但隨着ViewSets創建視圖集中實際合併所有上述操作,你也不要需要定義URL路徑,你通常使用路由器,使路徑,你喜歡:

#views.py 
class PostViewSet(ViewSet): #here you subclass Viwset check methods you can   override, you have also ModelViewSet,... 
# urls.py 
router = routers.DefaultRouter() 
router.register(r'post', PostViewSet, base_name='Post')