2017-11-17 164 views
0

我使用Django的REST框架構建的API,這裏是我的問題Django的REST框架相同的路線,不同的

url(r'^profiles/(?P<pk>[0-9]*)', ProfileRetrieveView.as_view(), name='profiles-detail'), 
url(r'^profiles/(?P<pk>[0-9]*)', ProfileUpdateView.as_view(), name='profiles-update'), 

class ProfileRetrieveView(RetrieveAPIView): 

    queryset = Profile.objects.all() 
    serializer_class = ProfileSerializer 

class ProfileUpdateView(UpdateAPIView): 

    queryset = Profile.objects.all() 
    serializer_class = ProfileSerializer 
    permission_classes = (IsAuthenticated,) 

當我查詢的API與鏈接/資料/ 2和方法補丁,我收到405,方法不允許,只允許get方法,我怎麼能解決這個問題,沒有避風港把我的兩個視圖類轉換成類與GenericView基類和Retrive +更新Mixins。

+0

這是URL匹配是如何工作的?它的股價下跌l ist並選擇匹配的第一個。正確的做法是讓一個類處理它。但在路由器配置中,如果我記得正確,可以將不同的方法路由到不同的類,但是您需要URL匹配一次。 – bryan60

回答

0

您應該將其壓縮爲單個端點。你可以讓一個類處理所有的列表,更新,獲取等等。嘗試...像這樣:

from rest_framework import mixins, viewsets 
class ProfileUpdateView(viewset.ModelViewSet, 
         mixins.ListModelMixin, 
         mixins.UpdateModelMixin): 

    serializer_class = ProfileSerializer 
    permission_classes = (IsAuthenticated,) 

    get_queryset(self): 
      return Profile.objects.all() 

如果你使用純模型,使用內置模型的東西,並檢查混合。它將爲您節省通用代碼編寫的噸。它有一些知道如何將請求路由到匹配的http方法的魔法。

http://www.django-rest-framework.org/api-guide/generic-views/#mixins

0

Django的REST框架提供了通用視圖,你不需要混入。 您可以直接使用RetrieveUpdateAPIView。提供請求方法get檢索數據,put更新數據和patch進行部分更新。

from rest_framework.generics import RetrieveUpdateAPIView 

class ProfileUpdateView(RetrieveUpdateAPIView): 
    queryset = Profile.objects.all() 
    serializer_class = ProfileSerializer 
    permission_classes = (IsAuthenticated,) 

參考:http://www.django-rest-framework.org/api-guide/generic-views/#retrieveupdateapiview

1

urls.py

url(r'^profiles/(?P<pk>[0-9]*)', ProfileRetrieveUpdateView.as_view(), name='profiles-detail-update'), 

views.py

from rest_framework.generics import RetrieveUpdateAPIView 

class ProfileRetrieveUpdateView(RetrieveUpdateAPIView): 

    queryset = Profile.objects.all() 
    serializer_class = ProfileSerializer 

    def get_permissions(self): 
     if self.request.method == "GET": 
      return [] 
     else: 
      return [IsAuthenticated()] 
相關問題