我正在尝试创建一个包含多个子应用的 django 应用。我当前的应用程序目录布局是(为简洁起见,过滤掉了 admin.py、test.py 和 views.py):
myapp
__init__.py
models.py
subapp1/
__init__.py
models.py
subapp2
__init__.py
models.py
myapp /models.py如下所示:
class Foo(models.Model):
name = models.CharField(max_length=32)
和myapp/subapp1/models.py看起来像:
class Bar(models.Model):
foo = models.ForeignKey('myapp.Foo')
some_other_field = models.CharField(max_length=32)
和myapp/subapp2/models.py看起来像:
class Baz(models.Model):
bar = models.ForeignKey('subapp1.Bar')
在我的settings.py 中,我有:
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'myapp',
'myapp.subapp1',
'myapp.subapp2'
)
但是,当我尝试运行时./manage.py makemigrations myapp.subapp1
,出现错误:
App 'myapp.subapp1' could not be found. Is it in INSTALLED_APPS?
但我能够成功运行./manage.py makemigrations subapp1
subapp2 的等效项。我担心的是应用程序命名空间冲突。
如果我添加一个myapp/subapp1/apps.py
from django.apps import AppConfig
class SubApp1Config(AppConfig):
name = 'myapp.subapp1'
label = 'myapp.subapp1'
然后到myapp/subapp1/__init__.py
default_app_config = 'myapp.subapp1.apps.SubApp1Config'
对 'myapp/subapp2' 执行等效操作并注释掉 'myapp.app2'INSTALLED_APPS
然后我可以./manage.py makemigrations myapp.subapp1
成功运行。
但是,如果我myapp.subapp2
从 INSTALLED_APPS取消注释
并将myapp/subapp2/models.py更改为:
class Baz(models.Model):
bar = models.ForeignKey('myapp.subapp1.Bar')
然后运行./manage.py makemigrations myapp.subapp2
我得到:
SystemCheckError: System check identified some issues:
ERRORS:
myapp.subapp2.Baz.bar: (fields.E300) Field defines a relation with model 'myapp.subapp1.Bar', which is either not installed, or is abstract.
我应该如何描述myapp.subapp2.Baz.bar
和之间的外键关系myapp.subapp1.Bar
?
提前致谢。