Django rest 允许获取但不列出
Django rest allow get but not list
我想允许 get
为来宾用户检索单个对象。但是保留 list
仅供管理员在数据库中检索该模型的所有项目。但我不确定如何将 get
和 list
分开,因为从我的角度来看,它们似乎都在 get
之下。
下面是我的视图集:
class OrdersViewSet(viewsets.ModelViewSet):
permission_classes = [IsAuthenticated|ReadOnly]
serializer_class = OrderSerializer
queryset = Order.objects.all()
# parser_classes = (MultiPartParser,)
model = Order
def update(self, request, *args, **kwargs):
kwargs['partial'] = True
return super().update(request, *args, **kwargs)
还有我的只读:
from rest_framework.permissions import BasePermission, IsAuthenticated, SAFE_METHODS
class ReadOnly(BasePermission):
def has_permission(self, request, view):
return request.method in SAFE_METHODS
您可以使用 get_permission
函数和 action
。
class OrdersViewSet(viewsets.ModelViewSet):
permission_classes = [IsAuthenticated|ReadOnly]
serializer_class = OrderSerializer
queryset = Order.objects.all()
# parser_classes = (MultiPartParser,)
model = Order
def update(self, request, *args, **kwargs):
kwargs['partial'] = True
return super().update(request, *args, **kwargs)
def get_permissions(self):
if self.action == 'list':
permission_classes = [IsAdmin]
elif self.action == 'retrieve':
permission_classes = [AllowAny]
else:
permission_classes = [ReadOnly]
return [permission() for permission in permission_classes]
我想允许 get
为来宾用户检索单个对象。但是保留 list
仅供管理员在数据库中检索该模型的所有项目。但我不确定如何将 get
和 list
分开,因为从我的角度来看,它们似乎都在 get
之下。
下面是我的视图集:
class OrdersViewSet(viewsets.ModelViewSet):
permission_classes = [IsAuthenticated|ReadOnly]
serializer_class = OrderSerializer
queryset = Order.objects.all()
# parser_classes = (MultiPartParser,)
model = Order
def update(self, request, *args, **kwargs):
kwargs['partial'] = True
return super().update(request, *args, **kwargs)
还有我的只读:
from rest_framework.permissions import BasePermission, IsAuthenticated, SAFE_METHODS
class ReadOnly(BasePermission):
def has_permission(self, request, view):
return request.method in SAFE_METHODS
您可以使用 get_permission
函数和 action
。
class OrdersViewSet(viewsets.ModelViewSet):
permission_classes = [IsAuthenticated|ReadOnly]
serializer_class = OrderSerializer
queryset = Order.objects.all()
# parser_classes = (MultiPartParser,)
model = Order
def update(self, request, *args, **kwargs):
kwargs['partial'] = True
return super().update(request, *args, **kwargs)
def get_permissions(self):
if self.action == 'list':
permission_classes = [IsAdmin]
elif self.action == 'retrieve':
permission_classes = [AllowAny]
else:
permission_classes = [ReadOnly]
return [permission() for permission in permission_classes]