[Django]-Add some parameters to FilterSet (django-filter) + some parameters

1👍

You can handle this in the FilterSet.__init__ method. Something like the below (Note that I haven’t tested it, may require some fiddling):

class ProductsFilter(django_filters.FilterSet):
    subcategory= django_filters.ChoiceFilter(lookup_expr='iexact', choices=[], required=False)

    def __init__(self, category, *args, **kwargs):
        super(ProductsFilter, self).__init__(*args, **kwargs)

        choices = self.fields['subcategory'].extra['choices']
        choices += [
            (subcat.name, subcat.name) for subcat 
            in SubCategory.objects.filter(category=category)
        ]

    class Meta:
        model = Products
👤Sherpa

2👍

The answer from @Sherpa has just two slight problems. First, you should replace fields with filters. Second, you can’t use += operator, you have to directly assign to the filter’s extra.
Here’s my working code in two different ways

class LayoutFilterView(filters.FilterSet):
    supplier = filters.ChoiceFilter(
        label=_('Supplier'), empty_label=_("All Suppliers"),)

    def __init__(self, *args, **kwargs):
        super(LayoutFilterView, self).__init__(*args, **kwargs)

        # First Method
        self.filters['supplier'].extra['choices'] = [
            (supplier.id, supplier.name) for supplier in ourSuppliers(request=self.request)
        ]

        # Second Method
        self.filters['supplier'].extra.update({
            'choices': [(supplier.id, supplier.name) for supplier in ourSuppliers(request=self.request)]
        })

Originally posted here

Leave a comment