Django 视图跳过检查权限 类

Django view skips checking permission classes

我正在尝试根据以下条件过滤列表:

我有这个代码:

在views.py中:

class LinkListViewSet(viewsets.ModelViewSet,
                  generics.ListAPIView,
                  generics.RetrieveAPIView):
queryset = LinkList.objects.all()
serializer_class = LinkListSerializer
permission_classes = [IsOwnerOrPublic]

在permissions.py中:

class IsOwnerOrPublic(BasePermission):
def has_permission(self, request, view):
    return request.user and request.user.is_authenticated

def has_object_permission(self, request, view, obj):
    return obj.owner == request.user or (
        obj.public and (request.method in SAFE_METHODS))

问题是,我认为该视图只是跳过检查权限 类 和 returns 所有列表,我不确定为什么或如何修复它。

它只会检查 has_object_permission 是否有使用对象的请求,例如 RetrieveAPIView,而不是 ListAPIView

你应该过滤后者,这样我们就可以制作自定义 IsOwnerOrPublicFilterBackend 过滤器后端:

from django.db.models import Q
from rest_framework import filters

class IsOwnerOrPublicFilterBackend(filters.BaseFilterBackend):
    
    def filter_queryset(self, request, queryset, view):
        return queryset.filter(<strong>Q(owner=request.user) | Q(public=True)</strong>)

然后在 ModelViewSet:

中将该过滤器用作 filter_backend
class LinkListViewSet(viewsets.ModelViewSet):
    queryset = LinkList.objects.all()
    serializer_class = LinkListSerializer
    <strong>filter_backends = [IsOwnerOrPublicFilterBackend]</strong>
    permission_classes = [IsOwnerOrPublic]