Given a model named MainModel
and a RelatedModel
, where the later has a ForeignKey
field to MainModel
:
class
Here is a piece of code I wrote when I was faced with the same problem. It is a bit brute force style, I guess, but is very agile and should suit all cases.
class MyModelAdmin(admin.ModelAdmin):
def __init__(self, *args, **kwargs):
super(MyModelAdmin, self).__init__(*args, **kwargs)
self.inline_instances_hash = {}
for inline_class in self.inlines:
for inline_instance in self.inline_instances:
if isinstance(inline_instance, inline_class):
break
self.inline_instances_hash[inline_class] = inline_instance
def get_inline_instance(self, inline_class):
return self.inline_instances_hash[inline_class]
def get_form(self, request, obj=None, **kwargs):
if obj:
self.inline_instances = []
if self.CONDITION:
self.inline_instances.append(self.get_inline_instance(
THE_INLINE_CLASS_I_WANT))
#...
else:
self.inline_instances = self.inline_instances_hash.values()