Sor*_*ona 7 django django-rest-framework
如何将ListCreateAPIView添加到路由器URL?
通常我喜欢:
router = routers.DefaultRouter()
router.register(r'busses', BusViewSet)
Run Code Online (Sandbox Code Playgroud)
但现在我有:
class CarList(generics.ListCreateAPIView): ...
Run Code Online (Sandbox Code Playgroud)
我现在把它添加到urlpatterns:
urlpatterns = patterns('',
url(r'^carts/', CarList.as_view(model=Car), name='cars'),
Run Code Online (Sandbox Code Playgroud)
我想添加这个Cars-view(如果我手动调用url,它正在按预期工作!)到路由器,所以它在概述页面中!
所以:它按原样工作,但我必须手动输入网址,它不在API的概述页面中.
原因是ViewSet
类与路由器一起使用的原因是在基础中GenericViewSet
具有a ViewSetMixin
。
ViewSetMixin
覆盖as_view()
方法,以便它采用一个actions
将HTTP方法绑定到Resource上的操作的关键字,并且路由器可以为操作方法建立映射。
您可以通过在类库中简单添加mixin来解决此问题:
from rest_framework.viewsets import ViewSetMixin
class CarList(ViewSetMixin, generics.ListCreateAPIView)
....
Run Code Online (Sandbox Code Playgroud)
但它不是因为明确的解决方案ListCreateAPIView
和ModelViewSet
它只是一个空班,在基地一堆混入的。因此,您始终可以ViewSet
使用所需的方法来构建自己的方法。
例如,以下代码ListCreateAPIView
:
class ListCreateAPIView(mixins.ListModelMixin,
mixins.CreateModelMixin,
GenericAPIView):
def get(self, request, *args, **kwargs):
return self.list(request, *args, **kwargs)
def post(self, request, *args, **kwargs):
return self.create(request, *args, **kwargs)
Run Code Online (Sandbox Code Playgroud)
在这里ModelViewSet
:
class ModelViewSet(mixins.CreateModelMixin,
mixins.RetrieveModelMixin,
mixins.UpdateModelMixin,
mixins.DestroyModelMixin,
mixins.ListModelMixin,
GenericViewSet):
pass
Run Code Online (Sandbox Code Playgroud)
请注意同一混入ListModelMixin
和CreateModelMixin
存在唯一的区别GenericViewSet
和GenericAPIView
。
GenericAPIView
使用方法名称并在其中调用操作。GenericViewSet
而是使用动作并将其映射到方法。
这是ViewSet
您需要的with方法:
class ListCreateViewSet(mixins.ListModelMixin,
mixins.CreateModelMixin,
GenericViewSet):
queryset_class = ..
serializer_class = ..
Run Code Online (Sandbox Code Playgroud)
现在,它可以与路由器一起使用list
,create
如果需要特殊行为,则可以覆盖和方法。
归档时间: |
|
查看次数: |
1016 次 |
最近记录: |