Django 管理命令文档显示了在 app/management/commands 文件夹中创建的所有命令。是否可以将命令放入子文件夹中,例如 app/management/commands/install 和 app/management/commands/maintenance?这将如何完成?
最佳答案
不幸的是,从 Django 1.4 开始,似乎没有办法做到这一点。 django.core.management.__init__.py
的来源有这个方法:
def find_commands(management_dir):
"""
Given a path to a management directory, returns a list of all the command
names that are available.
Returns an empty list if no commands are defined.
"""
command_dir = os.path.join(management_dir, 'commands')
try:
return [f[:-3] for f in os.listdir(command_dir)
if not f.startswith('_') and f.endswith('.py')]
except OSError:
return []
如您所见,它只考虑直接在 commands
中的文件。文件夹,忽略任何子文件夹。然而,如果你以某种方式“猴子补丁”这个函数,其余的代码应该可以正常工作,因为实际创建 Command
的代码实例是这样的:def load_command_class(app_name, name):
"""
Given a command name and an application name, returns the Command
class instance. All errors raised by the import process
(ImportError, AttributeError) are allowed to propagate.
"""
module = import_module('%s.management.commands.%s' % (app_name, name))
return module.Command()
所以,如果你有一个名为 subfolder.command
的命令它会加载正确的脚本并实例化正确的类。然而,从实际的角度来看,我认为这样做没有用。当然,拥有“命名空间”命令会很好,但是如果需要,您始终可以为所有命令添加一些名称作为前缀,使用其他名称作为分隔符(例如
_
)。命令名称长度 - 以及在终端中键入它们所需的击键次数 - 将相同......
关于Django:将管理命令拆分为子文件夹,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12125268/