Django rest框架-绑定到多个网址的基于单个类的视图

时间:2018-08-19 17:31:00

标签: django django-rest-framework

我正在创建一个供基于桌面的客户端使用的rest api。

我希望我的URL带有一个名为ProjectView的视图类:

 api.myapp.com/project/  -> uses ProjectView get
 api.myapp.com/project/create/  -> uses ProjectView post
 api.myapp.com/project/edit/  -> uses ProjectView put

如果不将所有其他操作(获取,发布,放置)暴露给该URL,我将无法将单个视图类绑定到多个URL。相反,我创建了ProjectView,ProjectViewCreate,ProjectViewEdit类,这似乎毫无意义。

无论如何,我是否可以完成用单个视图类概述的url配置?

2 个答案:

答案 0 :(得分:4)

嗯...也许这样的解决方案可能就足够了(根据需要修改您的项目模型):

from rest_framework import viewsets

class ProjectViewSet(viewsets.ViewSet):
    """
    A simple ViewSet for listing or retrieving, creating and updating projects.
    """
    def list(self, request):
       ....

    def create(self, request, pk=None):
       ....

    def update(self, request, pk=None):
       ....

然后在urls.py中

from myapp.views import ProjectViewSet
from rest_framework.routers import DefaultRouter

router = DefaultRouter()
router.register(r'project', UserViewSet.as_view({'get': 'list'}), base_name='projects')
router.register(r'project/create', UserViewSet.as_view({'post': 'create'}), base_name='project_create')
router.register(r'project/edit', UserViewSet.as_view({'put': 'update'}), base_name='project_update')

urlpatterns = router.urls

希望对您的代码和url结构进行一些修改-这将起作用!

答案 1 :(得分:0)

将视图定义为

from rest_framework.views import APIView
from rest_framework.response import Response


class ProjectView(APIView):

    def get(self, request, *args, **kwargs):
        # your code GET method code
        return Response("This is GET method")

    def post(self, request, *args, **kwargs):
        # your code POST method code
        return Response("This is POST method")

    def put(self, request, *args, **kwargs):
        # your code PUT method code
        return Response("This is PUT method")

,然后将您的urls.py更改为

urlpatterns = [
                  url(r'project/', ProjectView.as_view(), name='project_list'),
                  url(r'project/create/', ProjectView.as_view(), name='project_create'),
                  url(r'project/edit/', ProjectView.as_view(), name='project_edit')
              ]