Django 通用 api 视图中用于 CRUD 操作的相同 api 端点
Same api endpoint for CRUD operations in Django generic apiview
我一直在为不同的请求创建不同的 api 端点,例如每个 api 获取、post、删除和更新通用 api 视图。但是我的前端开发人员告诉我这是一个非常糟糕的做法,我需要为所有这 4 个请求设置一个 api。当我在文档中查找它时,有一个 ListCreateApiView 用于列出和创建对象,但我不能将它用于删除和更新。我怎样才能将这两个包含在一个端点中。我不使用模型集视图和功能视图。我主要使用通用 api 视图。
你试过rest framework的ModelViewSet
吗?
即:
from rest_framework.viewsets import ModelViewSet
它有所有的 mixins (CRUD),你可以在你的 API 视图中继承它。
或者您可以根据您的要求添加这些混入:
from rest_framework.mixins import CreateModelMixin, ListModelMixin, RetrieveModelMixin, UpdateModelMixin, DestroyModelMixin
并且您可以分别继承它们中的每一个。例如:
Class SomeView(CreateModelMixin, DestroyModelMixin, GenericViewSet):
pass
具有创建和删除功能。您还可以将 mixins 与 GenericAPIView
:
一起使用
Class SomeView(CreateModelMixin, DestroyModelMixin, GenericAPIView):
pass
我一直在为不同的请求创建不同的 api 端点,例如每个 api 获取、post、删除和更新通用 api 视图。但是我的前端开发人员告诉我这是一个非常糟糕的做法,我需要为所有这 4 个请求设置一个 api。当我在文档中查找它时,有一个 ListCreateApiView 用于列出和创建对象,但我不能将它用于删除和更新。我怎样才能将这两个包含在一个端点中。我不使用模型集视图和功能视图。我主要使用通用 api 视图。
你试过rest framework的ModelViewSet
吗?
即:
from rest_framework.viewsets import ModelViewSet
它有所有的 mixins (CRUD),你可以在你的 API 视图中继承它。 或者您可以根据您的要求添加这些混入:
from rest_framework.mixins import CreateModelMixin, ListModelMixin, RetrieveModelMixin, UpdateModelMixin, DestroyModelMixin
并且您可以分别继承它们中的每一个。例如:
Class SomeView(CreateModelMixin, DestroyModelMixin, GenericViewSet):
pass
具有创建和删除功能。您还可以将 mixins 与 GenericAPIView
:
Class SomeView(CreateModelMixin, DestroyModelMixin, GenericAPIView):
pass