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
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
- [Django]-Django / Python, calling a specific class / function on every user Request
- [Django]-Get the Sum of all fields in a Django queryset
- [Django]-How can i use 'set_password' in custom non-admin model?
- [Django]-Django pluralization functional.__proxy__object instead of verbose_name
- [Django]-How do I retrieve a value of a field in a queryset object
Source:stackexchange.com