Django REST Framework-如何返回404错误而不是403错误

Sam*_*uel 2 python django django-rest-framework

仅当用户通过身份验证并且满足某些其他条件时,我的API才允许访问(任何请求)。

class SomethingViewSet(viewsets.ModelViewSet):
    queryset = Something.objects.filter(query_hiding_non_authorized_objects)
    serializer_class = SomethingSerializer

    permission_classes = (permissions.IsAuthenticated, SomePermission)
Run Code Online (Sandbox Code Playgroud)

但是,如果用户尝试查看未经授权的对象,则DRF返回403错误,这表明存在具有所请求ID的对象。在这些情况下如何返回404错误?

注意:我还使用自定义查询集来隐藏未授权的对象,使其不被列出。

krs*_*krs 5

由于您已经将它们隐藏在get_queryset中,因此只需删除权限即可获得404。

编辑:您还可以在View类中重写Permission_denied方法以引发另一个异常,这是默认实现:

def permission_denied(self, request, message=None):
    """ If request is not permitted, determine what kind of exception to raise.
    """
    if request.authenticators and not request.successful_authenticator:
        raise exceptions.NotAuthenticated()
    raise exceptions.PermissionDenied(detail=message)
Run Code Online (Sandbox Code Playgroud)