11

I've got two models:

class Parent:
   ...

class Child:
   parent = models.ForeignKey(Parent)

In the model admin of the Parent I want to show an inline of the Child with a custom queryset, not only the ones related to the parent through the fk field.

I've tried:

class ChildInline(admin.TabularInline):
   model = Child
   def get_queryset(self, request):
      return Child.objects.filter(<my custom filter>)

class ParentAdmin(admin.ModelAdmin):
   inlines = [ChildInline]

But still the only children shown in the inline are the ones that fullfill both filters: related to the parent by the FK + my custom filter.

Is it possible to do this?

EDIT:

I've seen now is the BaseInlineFormSet who is filtering the queryset I compose to keep only childs related to the parent, any idea how to avoid this?

django/forms/models.py

class BaseInlineFormSet(BaseModelFormSet):
    ...
    if self.instance.pk is not None:
       qs = queryset.filter(**{self.fk.name: self.instance})
    ...
klautern
  • 129
  • 3
  • 7
  • 26

2 Answers2

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
    
hookedonwinter
  • 12,436
  • 19
  • 61
  • 74
Satendra
  • 6,755
  • 4
  • 26
  • 46
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
Linh Nguyen
  • 3,452
  • 4
  • 23
  • 67