Search code examples
djangodjango-adminencapsulation

How can I add inlines to the ModelAdmin of another app, without a circular dependency?


Let's say I have two models, in different apps. App Two knows about app One, but not the other way around:

# one/models.py

from django.db import models

class One(models.Model):
    pass


# two/models.py

from django.db import models
from one.models import One

class Two(models.Model):
    one = models.ForeignKey(One)

I also have One registered in the admin site:

# one/admin.py

from django.contrib import admin
from .models import One

admin.site.register(One)

How do I register Two as an Inline on One's admin page, without introducing a circular dependency between the two apps?


Solution

  • You can do this pretty simply, providing you don't mind accessing a 'private' attribute on the ModelAdmin. (Attributes beginning with an underscore are treated as private by convention.)

    # two/admin.py
    from django.contrib import admin
    from one.models import One
    from .models import Two
    
    class TwoInline(admin.StackedInline):
        model = Two
    
    admin.site._registry[One].inlines.append(TwoInline)