Hey there,
I’ve set up chained filters in Django Admin using foreign keys, but they don’t seem to update dynamically when a parent filter is selected. Has anyone experienced this issue before? What’s the proper way to implement chained filters in Django Admin to ensure they update correctly?
Thanks!
Welcome @Leerost !
Please post your Models involved with this, and the corresponding ModelAdmin classes.
Side Note: When posting code here, enclose the code between lines of three
backtick - ` characters. This means you’ll have a line of ```, then your code,
then another line of ```. This forces the forum software to keep your code
properly formatted.
One way to achieve this is to define the following filter:
class DependentListFilter(admin.RelatedFieldListFilter):
def __init__(self, field, request, params, model, model_admin, field_path):
super().__init__(field, request, params, model, model_admin, field_path)
query_params = {
self.dependent_field: id
for param, id in request.GET.items()
if param.startswith(self.dependent_field)
}
if query_params:
dep_field = self.dependent_field
filter = {dep_field + '__in': query_params[dep_field]}
self.lookup_choices = (
field.related_model.objects
.filter(**filter)
.values_list('id', 'name')
)
Assuming your model has the foreign keys continent
and country
, define the filter
class CountryListFilter(DependentListFilter):
dependent_field = 'continent'
Then in the model admin use the filter as follows:
@admin.register(MyModel)
class MyModelAdmin(admin.ModelAdmin):
list_display = ['continent', 'country']
list_filter = [
('continent', admin.RelatedFieldListFilter),
('country', CountryListFilter)
]