我有两个相互导入的类:
配置文件/models.py
class Company(models.Model):
name = ...
class CompanyReview(models.Model):
company = models.ForeignKey(Company)
from action.models import CompanyAction
action = models.ForeignKey(CompanyAction)
动作/models.py
from profile.models import Company
class CompanyAction(models.Model):
company = models.ForeignKey(Company, null = True, blank = True)
当在服务器上执行 Django 应用程序或在 shell 中调用视图函数时,循环导入有效。但是,当我导入其中一个类时,Django 命令将失败并出现错误(请参阅下面的 Traceback)。
为什么会出现这种情况并且只会在 中引起问题command method
?我怎样才能避免错误?我尝试过延迟导入CompanyAction
该类,但它导致了相同的错误消息。
不工作的替代方案:
class CompanyReview(models.Model):
company = models.ForeignKey(Company)
from django.db.models import get_model
_model = get_model('action', 'CompanyAction')
action = models.ForeignKey(_model)
有趣的是,如果我执行命令函数并且导入了类,则该变量_model
为空。当我加载./manage.py shell
时,变量包含正确的类名。为什么会这样?
追溯
(virtual-env)PC:neurix$ python manage.py close_action
Traceback (most recent call last):
File "manage.py", line 10, in <module>
execute_from_command_line(sys.argv)
File "/Users/Development/virtual-re/lib/python2.7/site-packages/django/core/management/__init__.py", line 453, in execute_from_command_line
utility.execute()
File "/Users/Development/virtual-re/lib/python2.7/site-packages/django/core/management/__init__.py", line 392, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/Users/Development/virtual-re/lib/python2.7/site-packages/django/core/management/__init__.py", line 272, in fetch_command
klass = load_command_class(app_name, subcommand)
File "/Users/Development/virtual-re/lib/python2.7/site-packages/django/core/management/__init__.py", line 77, in load_command_class
module = import_module('%s.management.commands.%s' % (app_name, name))
File "/Users/Development/virtual-re/lib/python2.7/site-packages/django/utils/importlib.py", line 35, in import_module
__import__(name)
File "/Users/Development/project/apps/action/management/commands/close_action.py", line 2, in <module>
from action.models import CompanyAction
File "/Users/Development/project/apps/action/models.py", line 26, in <module>
from profile.models import Company
File "/Users/Development/apps/profile/models.py", line 436, in <module>
class CompanyReview(models.Model):
File "/Users/Development/project/apps/profile/models.py", line 446, in CompanyReview
action = models.ForeignKey(_model)
File "/Users/Development/virtual-re/lib/python2.7/site-packages/django/db/models/fields/related.py", line 993, in __init__
assert isinstance(to, six.string_types), "%s(%r) is invalid. First parameter to ForeignKey must be either a model, a model name, or the string %r" % (self.__class__.__name__, to, RECURSIVE_RELATIONSHIP_CONSTANT)
AssertionError: ForeignKey(None) is invalid. First parameter to ForeignKey must be either a model, a model name, or the string 'self'