如何在 Django 休息框架中更改基于 request.query_params 的权限?

How to change permission based on request.query_params in Django rest frameworks?

我合并了两个除了权限之外几乎做同样事情的视图,我想更改权限基于:如果 company id 在参数中。如果没有,它将使用简单的 IsAuthenticated class 并为 IsCompany.

创建权限
class FilesView(ListAPIView):
    serializer_class = FileSerializer
    permission_classes = (IsAuthenticated,)
    ...
    
    def get_queryset(self):
        if 'company' in self.request.query_params:
            # In this case I want the IsCompany Permission class
            return get_company_files(self)
        # Otherwise the regular one
        return get_personal_files(self)

请参阅 DRF 文档中的 custom permissions

一个小例子:

from rest_framework import permissions

class IsCompanyRequestBasedPermission(permissions.BasePermission):
    message = '<description of your permission>'

    def has_permission(self, request, view):
        if 'company' in self.request.query_params:
            # Make your decision. 

然后将其添加到permission_classes。它会像您期望的那样工作。

如果你使用

class FilesView(ModelViewSet):

而不是

class FilesView(ListAPIView)

你可以使用get_serializer_class方法来帮助你 例如

def get_serializer_class(self):
    if "your statement":
        return "FirstSerializer"
    if "your statement":
        return "SecondSerializer"