Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

View list of only current user objects, Django REST

Tags:

python

django

I have 2 views: /notes/ and /notes// In note model in models.py I have owner variable, that stores owner's login. Because I want to have many users, I don't want them to see other's notes, so I created the permission:

class IsOwner(permissions.BasePermission):
    def has_object_permission(self, request, view, obj):
        return obj.owner == request.user

I set this permission to NotesList(generics.ListCreateAPIView) and NotesDetail(generics.RetrieveUpdateDestroyAPIView). Now user can't view other's notes if he will go to /notes/<pk>/, but in /notes/ he can view the full list anyway. So, how can I change it? I want to see in notes list only my notes. I think the right way is to filter queryset = Snippet.objects.all().filter(owner=...) but can't think right away.

like image 374
Mark Seliaev Avatar asked Dec 08 '22 18:12

Mark Seliaev


1 Answers

You are correct, you need to override the queryset in the list view. But you can't do that in the queryset attribute itself, because that is executed at process startup whereas you need access to data that is only available at request time. So you need to define the get_queryset method in that view:

def get_queryset(self, *args, **kwargs):
     return Snippet.objects.all().filter(owner=self.request.user)
like image 116
Daniel Roseman Avatar answered Jan 08 '23 08:01

Daniel Roseman