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})
...
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With