djangodjango-rest-frameworkdjango-permissions

DRF - how to implement object based permission on queryset?


I implemented DRF as per the document. At one point I figured out, once the user is authenticated, the user is allowed to fetch data of any user in the systems.

I have implemented filtering as per this document.

I read through the permission document and could not find a way to filter out queryset based on the owner. In my one of the views, I am checking if the owner is same as the user who requested.

My question is, Do I have to do the same in all viewsets? or There is a general way where I can check this condition?


Solution

  • Not sure, if it is the best way, but I do it by overriding get_queryset

    def get_queryset(self):
        queryset = YOUR_MODEL.objects.filter(user_id=self.request.user.id)
        return queryset
    

    Doing it, using permisson class

    class IsInUserHierarchy(permissons.BasePermission):
         def has_permission(self, request, view):
            return bool(isinstance(request.user, UserClassHierarchy))
    

    Some explanations. IsInUserHierarchy class is very similar to IsAdminUser. It checks, if request.user is in the required class (import UserClassHierarchy from models), using simple python isinstance() method