Given a model named MainModel
and a RelatedModel
, where the later has a ForeignKey
field to MainModel
:
class
From peeking at contrib.admin.options.py
Looks like you could override ModelAdmin.get_formsets
. Note that the admin site populates self.inline_instances
at __init__
, so you probably want to follow and not instantiate your inlines over and over. I'm not sure how expensive it is : )
def get_formsets(self, request, obj=None):
if not obj:
return [] # no inlines
elif obj.type == True:
return [MyInline1(self.model, self.admin_site).get_formset(request, obj)]
elif obj.type == False:
return [MyInline2(self.model, self.admin_site).get_formset(request, obj)]
# again, not sure how expensive MyInline(self.model, self.admin_site) is.
# the admin does this once. You could instantiate them and store them on the
# admin class somewhere to reference instead.
The original admin get_formsets
uses generators - you could too to more closely mimic the original:
def get_formsets(self, request, obj=None):
for inline in self.inline_instances:
yield inline.get_formset(request, obj)