Search code examples
djangodjango-generic-views

Limit queryset in generic views to objects with request.user as foreign key


I've had to add a method to just about UpdateView, DetailView, ListView, and DeleteView class in views.py to limit the queryset to only return objects that the logged in user is allowed to see (which in my case, means they are the foreignkey user on the object's model)

def get_queryset(self):
    base_qs = super(ViewName, self).get_queryset()
    return base_qs.filter(user=self.request.user)

Is there a more efficient way to do this with a Mixin or anything?


Solution

  • You can design your own mixin:

    class UserFilterViewMixin:
        user_field = 'user'
    
        def get_queryset(self):
            return super().get_queryset().filter(
                **{self.user_field: self.request.user}
        )

    Next you can use the mixin, for example with:

    from django.contrib.auth.mixins import LoginRequiredMixin
    
    class MyListView(UserFilterViewMixin, LoginRequiredMixin, ListView):
        model = MyModel

    You can set another user_field attribute in your views, if you need to filter on an owner=, created_by=, etc.