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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With