[Solved]-Django admin inline with custom queryset

11👍

The old answer doesn’t work anymore for current Django 2.2 or 3 because self.queryset get ignored

Current solution is to override the get_queryset:

from django.forms.models import BaseInlineFormSet

class ChildInlineFormSet(BaseInlineFormSet):

    def get_queryset(self):
        qs = super(ChildInlineFormSet, self).get_queryset()
        return qs.filter(<custom query filters>)

class ChildInline(admin.TabularInline):
    model = Child
    formset = ChildInlineFormSet
    extra = 0

14👍

You have to override __init__() method of BaseInlineFormSet and update queryset there.

from django.forms.models import BaseInlineFormSet

class ChildInlineFormSet(BaseInlineFormSet):

    def __init__(self, *args, **kwargs):
        super(ChildInlineFormSet, self).__init__(*args, **kwargs)
        # Now we need to make a queryset to each field of each form inline
        self.queryset = Child.objects.filter(<my custom filter>)

Then initialise formset attribute with ChildInlineFormSet

class ChildInline(admin.TabularInline):
    model = Child
    formset = ChildInlineFormSet
    extra = 0
    

Leave a comment