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

9lowa7mx  于 2023-01-27  发布在  Go
关注(0)|答案(1)|浏览(98)

我有一个用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?

carvr3hs

carvr3hs1#

创建自定义权限类www.example.comhttps://www.django-rest-framework.org/api-guide/permissions/#custom-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

在www.example.com中Views.py

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

相关问题