Django admin display filter depending on other filters
I'm not sure if it's the best way to do it, but here I use the GET parameter of the url from the admin panel to get the ID of the book then I can select the corresponding chapters. And it works!
class ChapterFilter(admin.SimpleListFilter):
title = 'chapter'
parameter_name = 'chapter'
def lookups(self, request, model_admin):
if 'book__id__exact' in request.GET:
id = request.GET['book__id__exact']
chapters = set([c.chapter for c in model_admin.model.objects.all().filter(book=id)])
else:
chapters = set([c.chapter for c in model_admin.model.objects.all()])
return [(b.id, b.titre) for b in chapters]
def queryset(self, request, queryset):
if self.value():
return queryset.filter(chapter__id__exact=self.value())
class ExerciseAdmin(admin.ModelAdmin):
list_filter = (('book',admin.RelatedOnlyFieldListFilter), (ChapterFilter))