如何在管理员模块中制作类似注册模型的东西

2024-03-29 11:16:28 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试制作一个填充数据库的应用程序。 我在所有应用程序中创建了一个名为“filldata.py”的文件。 此文件导入包。 然后我实现了一个回调函数并在包中注册 filler.register(mycallback) 我有一个通用应用程序,在其中我实现了一个填充数据库的终端命令。 这类似于管理模块中注册模型的实现。 此代码是终端命令的实现。他不喜欢这样。我认为有一种更好的pythonic方法来实现这个导入

import importlib

from django.conf import settings
from django.core.management.base import BaseCommand


class Command(BaseCommand):
    def handle(self, *args, **options):
        filler = None
        for app in settings.INSTALLED_APPS:
            try:
                filler = importlib.import_module(app + '.filldata')
            except ImportError:
                pass
        if filler:
            filler.filler.sort_callbacks()
            for msg in filler.filler.fill():
                self.stdout.write(self.style.SUCCESS(msg))

Tags: 文件djangofromimport命令self数据库应用程序