如何在没有循环依赖的情况下向其他应用程序的ModelAdmin添加内联? [英] How can I add inlines to the ModelAdmin of another app, without a circular dependency?

查看:62
本文介绍了如何在没有循环依赖的情况下向其他应用程序的ModelAdmin添加内联?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我在不同的应用程序中有两个模型.应用二了解应用一,但反之则不了解:

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)

如何在 One 的管理页面上将 Two 注册为内联,而又不会在两个应用之间引入循环依赖关系?

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

推荐答案

只要您不介意访问 ModelAdmin 上的"private"属性,就可以非常简单地完成此操作.(以下划线开头的属性按照惯例被视为私有.)

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)

这篇关于如何在没有循环依赖的情况下向其他应用程序的ModelAdmin添加内联?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆