django - 执行命令时的循环导入问题

时间:2021-07-11 16:56:59

I'm developing a django application. Modules of importance to my problem are given below:

我正在开发一个django应用程序。对我的问题很重要的模块如下:

globals.py --> contains constants that are used throughout the application. SITE_NAME and SITE_DOMAIN are two of those and are used to fill some strings. Here is how I define them:

globals.py - >包含整个应用程序中使用的常量。 SITE_NAME和SITE_DOMAIN是其中两个,用于填充一些字符串。以下是我如何定义它们:

from django.contrib.sites.models import Site
...
SITE_DOMAIN = Site.objects.get_current().domain
SITE_NAME = Site.objects.get_current().name

models.py --> models live inside this module. imports some constants from globals.py

models.py - >模型存在于此模块中。从globals.py导入一些常量

some_command.py --> a command that imports some constants from globals also.

some_command.py - >一个从全局变量中导入一些常量的命令。

when executed, the command imports a constant from globals.py and runs into a circular import problem: inside globals.py, get_current() from sites app is called, and sites app in turn imports models.py which has imports from globals.py as well.

执行时,该命令从globals.py导入一个常量并运行循环导入问题:在globals.py内部调用来自sites app的get_current(),而sites app依次导入models.py,其中包含从globals.py导入的内容。同样。

EDIT:

编辑:

The application runs flawlessly, without encountering this circular import issue. Importing globals.py from shell brings no problems. Even the command can be executed from the shell without calling manage.py.

应用程序运行完美,没有遇到此循环导入问题。从shell导入globals.py不会带来任何问题。甚至可以在不调用manage.py的情况下从shell执行命令。

So why does manage.py some_command fail due to a circular import?

那么为什么manage.py some_command因循环导入而失败?

Thanks in advance.

提前致谢。

1 个解决方案

#1


1  

Is there any particular reason you need to store SITE_DOMAIN and SITE_NAME in globals.py? These are already available directly from the sites framework.

您是否需要在globals.py中存储SITE_DOMAIN和SITE_NAME?这些已经可以直接从站点框架中获得。

According to the docs, the site object is cached the first time you access it, so importing it and using it there directly doesn't hurt.

根据文档,站点对象在您第一次访问它时被缓存,因此导入它并直接在那里使用它并没有伤害。

#1


1  

Is there any particular reason you need to store SITE_DOMAIN and SITE_NAME in globals.py? These are already available directly from the sites framework.

您是否需要在globals.py中存储SITE_DOMAIN和SITE_NAME?这些已经可以直接从站点框架中获得。

According to the docs, the site object is cached the first time you access it, so importing it and using it there directly doesn't hurt.

根据文档,站点对象在您第一次访问它时被缓存,因此导入它并直接在那里使用它并没有伤害。