Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django admin inline with custom queryset

Tags:

django

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})
    ...
like image 698
klautern Avatar asked Sep 27 '17 12:09

klautern


1 Answers

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
like image 169
Linh Nguyen Avatar answered Oct 03 '22 18:10

Linh Nguyen