如果多个Django应用定义相同的自定义管理命令,使用哪个?
If multiple Django apps define the same custom management command, which is used?
docs 对此问题保持沉默。命令是否会按顺序注册,后面的应用程序(按 settings.INSTALLED_APPS
顺序)会覆盖以前的命令(无论是来自其他应用程序的自定义命令还是内置的 Django 命令)?
从当前的 1.7 版本开始,答案是肯定的。
参见this line in the Django source to see where the logic is implemented: in the order of apps per the settings.INSTALLED_APPS
tuple, each app's management commands are added to a dictionary of commands (which was initialized with Django's built-in commands here), with a single slot for any given command name, so that last one added sticks, overriding any previous app's (or Django's built-in) command with the same name; when executing a command (code here),Django 使用上面的字典来决定实际使用哪个命令逻辑。
请注意,我还没有找到这方面的任何文档,因此从技术上讲,它应该被视为非官方行为。
命令以 反向 应用顺序注册(参见 here)。因此,要在应用程序 foo
中用您自己的版本覆盖应用程序 bar
中的 FooCommand
,bar
必须 优先于 foo
settings.INSTALLED_APPS
.
这很不幸,因为您可能出于其他原因需要 bar
来关注 foo
。例如,如果 bar
的模型引用 foo
的模型。
如果可行,一个解决方案是将覆盖命令拆分到一个单独的应用程序中。
来自Django 2.2 official documentation
When several applications provide different versions of the same resource (template, static file, management command, translation), the application listed first in INSTALLED_APPS has precedence.
docs 对此问题保持沉默。命令是否会按顺序注册,后面的应用程序(按 settings.INSTALLED_APPS
顺序)会覆盖以前的命令(无论是来自其他应用程序的自定义命令还是内置的 Django 命令)?
从当前的 1.7 版本开始,答案是肯定的。
参见this line in the Django source to see where the logic is implemented: in the order of apps per the settings.INSTALLED_APPS
tuple, each app's management commands are added to a dictionary of commands (which was initialized with Django's built-in commands here), with a single slot for any given command name, so that last one added sticks, overriding any previous app's (or Django's built-in) command with the same name; when executing a command (code here),Django 使用上面的字典来决定实际使用哪个命令逻辑。
请注意,我还没有找到这方面的任何文档,因此从技术上讲,它应该被视为非官方行为。
命令以 反向 应用顺序注册(参见 here)。因此,要在应用程序 foo
中用您自己的版本覆盖应用程序 bar
中的 FooCommand
,bar
必须 优先于 foo
settings.INSTALLED_APPS
.
这很不幸,因为您可能出于其他原因需要 bar
来关注 foo
。例如,如果 bar
的模型引用 foo
的模型。
如果可行,一个解决方案是将覆盖命令拆分到一个单独的应用程序中。
来自Django 2.2 official documentation
When several applications provide different versions of the same resource (template, static file, management command, translation), the application listed first in INSTALLED_APPS has precedence.