2013-06-29 106 views
2

我有两个应用程序,commonappapp1Django:摆脱循环依赖

这里的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) 

当我尝试从任一app1commonapp运行SQL,我得到以下错误:

$ 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. 

我意识到这是一个问题的循环依赖。其他人建议将类路径指定为string而不是实际的类,但这不起作用。我也不能指定一个字符串作为派生类中的基类名。

没有重构我的模型,这样的循环依赖可能吗?

+0

把SomeFields放在app1/models.py – lalo

+0

我不想这样做。我可以将所有内容放在一个models.py中,但我想避免这样做。该项目由不同的人开发,每个人都被分配了一个应用程序。考虑到开发组织和模型的逻辑应用程序位置,它使得模型变得更加清洁,以使模型处于不同的应用程序中。 – user2233706

+0

你的应用程序是什么? – lalo

回答

6

导入app1.models介于CommonFieldsSomeFields之间的某处。

+0

哇,你一定是在开玩笑吧。我无法相信这是行得通的。谢谢。 – user2233706

+0

@ user2233706你真的应该尝试解决循环依赖问题。如果'common'真的很常见,那么它不应该依赖于'specific'的东西。 –

+0

我明白了。问题是我有另一个应用程序,依赖于'common',但不是'app1'。 – user2233706