Django:摆脱循环依赖 [英] Django: getting rid of circular dependency
问题描述
我有两个应用程序, commonapp
和 app1
。
I have two apps, commonapp
and app1
.
这里是来自django的 commonapp / models.py
:
Here's commonapp/models.py
:
from django.db import models
#from app1.models import SpecificFields
# Create your models here.
class CommonFields(models.Model):
a = models.IntegerField(default = 0)
class Meta:
abstract = True
class SomeFields(models.Model):
# a = models.ForeignKey(SpecificFields)
a = models.ForeignKey('app1.models.SpecificFields')
这里的 app1 / models.py
:
from django.db import models
from commonapp.models import CommonFields
# Create your models here.
class SpecificFields(CommonFields):
a2 = models.IntegerField(default=0)
当我尝试从 app1
或 commonapp
运行SQL时,我收到以下错误: p>
When I try to run the SQL from either app1
or commonapp
, I get the following error:
$ python manage.py sql commonapp
CommandError: One or more models did not validate:
commonapp.somefields: 'a' has a relation with model app1.models.SpecificFields,
which has either not been installed or is abstract.
我意识到这是循环依赖的问题。其他人建议将类别的路径指定为字符串,而不是实际的类,但是那不行。我也不能在派生类中指定一个字符串作为基类名。
I realize this is an issue of a circular dependency. Others have suggested of specifying the path to a class as a string instead of the actual class, but that does not work. I also cannot specify a string as the base class name in the derived class.
是否可以在没有重构我的模型的情况下执行循环依赖?
Is such a circular dependency possible without refactoring my models?
推荐答案
在 CommonFields
之间的某个地方导入 app1.models
和 SomeFields
。
Import app1.models
somewhere between CommonFields
and SomeFields
.
这篇关于Django:摆脱循环依赖的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!