PUT
并且PATCH
都是同一个mixin(UpdateModelMixin)的一部分。
所以如果我像这样扩展它:
class UserViewSet(mixins.UpdateModelMixin, GenericViewSet):
queryset = User.objects.all()
serializer_class = UserSerializer
两者PUT
都PATCH
允许。我想根本不允许PUT
我的应用程序(因为PATCH
已经完成了工作,并且我想使用 just 来限制对象创建POST
)。一种方法是创建权限:
class NoPut(permissions.BasePermission):
"""
PUT not allowed.
"""
message = 'You do not have permission to complete the action you are trying to perform.'
def has_object_permission(self, request, view, obj):
if view.action == "update":
return False
return True
并将此权限授予我所有允许PATCH
. 这是最好的方法吗?有没有更优选的方式?
编辑:查看@wim提供的答案后,这是否是一个很好的解决方案(除了put
删除映射之外,一切都保持不变):
from rest_framework.routers import SimpleRouter
class NoPutRouter(SimpleRouter):
routes = [
# List route.
Route(
url=r'^{prefix}{trailing_slash}$',
mapping={
'get': 'list',
'post': 'create'
},
name='{basename}-list',
initkwargs={'suffix': 'List'}
),
# Dynamically generated list routes.
# Generated using @list_route decorator
# on methods of the viewset.
DynamicListRoute(
url=r'^{prefix}/{methodname}{trailing_slash}$',
name='{basename}-{methodnamehyphen}',
initkwargs={}
),
# Detail route.
Route(
url=r'^{prefix}/{lookup}{trailing_slash}$',
mapping={
'get': 'retrieve',
# put removed
'patch': 'partial_update',
'delete': 'destroy'
},
name='{basename}-detail',
initkwargs={'suffix': 'Instance'}
),
# Dynamically generated detail routes.
# Generated using @detail_route decorator on methods of the viewset.
DynamicDetailRoute(
url=r'^{prefix}/{lookup}/{methodname}{trailing_slash}$',
name='{basename}-{methodnamehyphen}',
initkwargs={}
),
]
还是我需要重新定义其他方法SimpleRoute
(例如__init()__
, get_routes()
,_get_dynamic_routes()
等get_method_map()
)以使其正常工作?