Mark Seliaev
Mark Seliaev

Reputation: 570

View list of only current user objects, Django REST

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.

Upvotes: 5

Views: 3869

Answers (1)

Daniel Roseman
Daniel Roseman

Reputation: 599580

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)

Upvotes: 17

Related Questions