[Django]-Limit queryset in generic views to objects with request.user as foreign key

4👍

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.

Leave a comment