Django的REST框架相同的路线,不同的
问题描述:
我使用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。
答
您应该将其压缩为单个端点。你可以让一个类处理所有的列表,更新,获取等等。尝试...像这样:
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
答
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
答
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()]
这是URL匹配是如何工作的?它的股价下跌l ist并选择匹配的第一个。正确的做法是让一个类处理它。但在路由器配置中,如果我记得正确,可以将不同的方法路由到不同的类,但是您需要URL匹配一次。 – bryan60