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})
    ...
0

2 Answers 2

15
+50

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
    
5
  • 1
    Didn´t work. What I need is to ignore the superclass filter that uses the FK field.
    – klautern
    Commented Nov 13, 2017 at 10:36
  • I have updated my answer. please check and let me know if this worked?
    – Satendra
    Commented Nov 13, 2017 at 11:38
  • What if we need access to the request or user object?
    – bparker
    Commented Jul 23, 2019 at 16:19
  • 1
    It does not work in Django 2.2.5. self.queryset is ignored. I always get all data Commented Sep 25, 2019 at 12:01
  • @hipertracker please use .get_queryset() instead of .queryset
    – xjlin0
    Commented Nov 11, 2020 at 17:06
14

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
2

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.