开发者

Model imports failing between apps in django (circular imports?)

I am having problems importing models between my apps in my current django project. When trying to run the dev server or sync the database, I receive the error:

File "/path/to/Project/../Project/app1/models.py", line 3, in <module>
class SomeModel(Thing):
NameError: name 'Thing' is not defined

Thing is defined in Project/main/models.py which I import into Project/app1/models.py via:

from project.main.models import Thing

I am aware that this sort of thing can be the result of python preventing circular imports.

Currently I have three django apps: main, app1, app2

The imports for each app are like so:

main:

from project.app1.models import AnotherThing

app1:

from project.main.models import Thing

app2:

from project.main.models import Thing
from project.app1 import Something

I suspect that importing models from app1 into app2 is causing the problem, since both of those apps import models from main, which in turn imports models from app1, etc.

If this is the case - what other methods can I use to achieve the same effect as these imports? Is there a more accepted way of organizing things so t开发者_运维技巧hat I won't run into this?


If you want to subclass those models, you need to remove circular dependency. Refactor common stuff into another module, and make those two import that instead of each other. If the model is only used as a foreign key, you can use string instead of an object to defer the import (e.g. ForeignKey('app.Model') — see documentation for details).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜