Given a model named MainModel
and a RelatedModel
, where the later has a ForeignKey
field to MainModel
:
class
This worked for me while searching for an answer to the same problem in this old post.
Expanding upon darklow's answer , I think you can simply override get_inline_instances
completely and add an extra check based on your type.
Add a boolean type check method in your model
class MainModel(models.Model):
name = models.CharField(max_length=50)
type = models.BooleanField()
def is_type1(self):
return type=="some value"
def is_type2(self):
return type=="some value"
Add inline instance base on type check - Simply copy and paste the get_inline_insances method from the parent class into your admin.ModelAdmin class and add the if block to check the model type as shown below
class MyModelAdmin(admin.ModelAdmin):
inlines = [RelatedModel1, RelatedModel2]
def get_inline_instances(self, request, obj=None):
inline_instances = []
if not obj:
return []
for inline_class in self.inlines:
inline = inline_class(self.model, self.admin_site)
if request:
if not (inline.has_add_permission(request) or
inline.has_change_permission(request, obj) or
inline.has_delete_permission(request, obj)):
continue
if not inline.has_add_permission(request):
inline.max_num = 0
if obj.is_type1() and isinstance(inline,RelatedModel1InlineAdmin):
inline_instances.append(inline)
if obj.is_type2() and isinstance(inline,RelatedModel2InlineAdmin):
inline_instances.append(inline)
return inline_instances