how to filter in django admin inlines

4.6k Views Asked by At
class StudentsTeacher(admin.TabularInline):
    form = StudentsTeacher
    model = StudentsTeacher

class Teacher_Admin(admin.ModelAdmin):
    inlines = (StudentsTeacher,)

I want add a queryset in StudentsTeacher select with a filter, but it doesn't work, inlines always dispay all.

2

There are 2 best solutions below

2
On

With the get_queryset() method you can override the queryset

class Teacher_Admin(admin.TabularInline):
    def get_queryset(self, request):
        qs = super(Teacher_Admin, self).get_queryset(request)
        return qs.filter(<filtering>)

You can read more about it in the django docs

1
On

You can also define your custom queryset in the formset for inlines

    class StudentTeacherFormset(BaseInlineFormSet):
        self.queryset = StudentsTeacher.objects.filter(<your custom filter>)

    class StudentsTeacher(admin.TabularInline):
        form = StudentsTeacher
        model = StudentsTeacher
        formset = StudentTeacherFormset

    class Teacher_Admin(admin.ModelAdmin):
        inlines = (StudentsTeacher,)

Formset can be used to generate a custom queryset for django inlines instead of rendering all the objects of child table in parents admin.

However if anyone finds a solution for providing a filter in django inlines similar to list filter, please let me know.