[Django]-Customize queryset in django-filter ModelChoiceFilter (select) and ModelMultipleChoiceFilter (multi-select) menus based on request

8👍

After hours of search, I found the solution in the official documentation here!

The queryset argument for ModelChoiceFilter and ModelMultipleChoiceFilter supports callable behavior. If a callable is passed, it will be invoked with the request as its only argument.

import django_filters as filters
from django.utils.translation import gettext as _

def ourBranches(request):
    if request is None:
        return Branch.objects.none()

    company = request.user.profile.company
    return Branch.objects.filter(company=company)


class UnitFilter(filters.FilterSet):
    branch = filters.ModelChoiceFilter(
        queryset=ourBranches, empty_label=_("All Branches"))

    class Meta:
        model = Unit
        fields = ('branch', )

and in the view, I made sure to pass the request as well

 qs = Unit.objects.all()
 filter = UnitFilter(self.request.GET, request=self.request, queryset=qs) 
 table = UnitTable(filter.qs)

3👍

I also had problems finding a resolution to this.

I solved it (I think) via the following:

views.py

table_filter = ExampleFilter(request.GET, kwarg_I_want_to_pass=request.user, queryset=qs)

filters.py

class ExampleFilter(django_filters.FilterSet):

    def __init__(self, *args, **kwargs):
        self.user = kwargs.pop('kwarg_I_want_to_pass', None)
        super(ExampleFilter, self).__init__(*args, **kwargs)

        self.filters['field_to_filter'].extra.update({
           'queryset': Supplier.objects.filter(related_user=self.user),
           'empty_label': '',
           'help_text': False
        })

    class Meta:
        model = ExampleModel
        fields = ['related_user', 'field_to_filter', ... other fields]

Leave a comment