如何在DRF条件语句的视图集中写权限?



我有一个用DRF写的视图集:

class MyViewSet(ModelViewSet):
serializer_class = MySerializer
queryset = models.MyClass.objects.all()
def get_serializer_class(self):
permission = self.request.user.permission
if permission=='owner' or permission=='admin': 
return self.serializer_class
else:
return OtherSerializer
def perform_create(self, serializer):
permission = self.request.user.permission
if permission=='owner' or permission=='admin': 
serializer.save() 
else:
employee = models.Employee.objects.get(user=self.request.user)
serializer.save(employee=employee)

这里,我在get_serializer_class和perform_create中使用以下语句,这看起来像一个重复的代码:

permission = self.request.user.permission
if permission=='owner' or permission=='admin': 

有没有办法写一次,然后以某种方式使用它作为permission_class ?

创建自定义权限类https://www.django-rest-framework.org/api-guide/permissions/定制权限

from rest_framework.permissions import BasePermission, SAFE_METHODS
class CustomPermission(BasePermission):
def has_permission(self, request, view):
if request.method in SAFE_METHODS:
return True
permission = self.request.user.permission
if permission=='owner' or permission=='admin': 
return True
return False 

在Views.py

class MyViewSet(ModelViewSet):
serializer_class = MySerializer
queryset = models.MyClass.objects.all()
permission_classes = (CustomPermission,)

相关内容

  • 没有找到相关文章

最新更新