在子目录而不是 admin.py 中定义 Django 管理模型

Defning Django admin models inside subdirectories instead of admin.py

我的目标是在单独的文件中定义管理模型。所以项目结构是这样的:

应用程序

admin_models
       __init__.py
       TestAdmin.py

TestAdmin.py:

from django.contrib import admin
from cms.models import (
    TestModel)


class TestAdmin(admin.ModelAdmin):
    fields = (...)


admin.site.register(TestModel, TestAdmin)

问题是模型没有出现在管理页面上。但是,在标准结构中(如果我将 TestAdmin.py 文件的内容移动到应用程序内顶层的 admin.py),那么一切正常。无论如何要解决这个问题?

Django 的内部结构(例如 "autodiscovery") rely on a certain app structure. Part of that is that the admin namespace within an installed app is imported at app loading time (in the AppConfig.ready 方法)。所以你可以制作一个像这样的包结构:

app
    admin
        __init__.py
        test_admin.py  # different from admin class name!
        another_admin.py

在您的 test_admin.py 中,您可以像以前一样定义 TestAdmin class。在包的 __init__.py 中,您从子模块中导入管理员:

# __init__.py
from .test_admin import TestAdmin
from .other_admin import YetAnotherAdmin

这样,您就可以构建您的代码库,并且 django 的内部工作仍会在模型管理员所在的位置注册模型管理员。

正如@Alasdair 所指出的,您还可以"manually" 在自定义 AppConfig 中导入自定义管理模块。如果您还没有,我会坚持使用上述方法,因为它不需要在各个地方进行更改(INSTALLED_APPSapp/__init__.pyapp/apps.py、...)这可能会产生无法预料的副作用。