ImportError: Model A references Model B, Model B references Model A
I think this is more a python question than Django.
But basically I'm doing at Mo开发者_Go百科del A:
from myproject.modelb.models import ModelB
and at Model B:
from myproject.modela.models import ModelA
Result:
cannot import name ModelA
Am I doing something forbidden? Thanks
A Python module is imported by executing it top to bottom in a new namespace. When module A imports module B, the evaluation of A.py is paused until module B is loaded. When module B then imports module A, it gets the partly-initialized namespace of module A -- in your case, it lacks the ModelA
class because the import of myproject.modelb.models
happens before the definition of that class.
In Django you can fix this by referring to a model by name instead of by class object. So, instead of saying
from myproject.modela.models import ModelA
class ModelB:
a = models.ForeignKey(ModelA)
you would use (without the import):
class ModelB:
a = models.ForeignKey('ModelA')
Mutual imports usually mean you've designed your models incorrectly.
When A depends on B, you should not have B also depending on A.
Break B into two parts.
B1 - depends on A.
B2 - does not depend on A.
A depends on B1. B1 depends on B2. Circularity removed.
精彩评论