Question

I think this is more a python question than Django.

But basically I'm doing at Model 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

Was it helpful?

Solution

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')

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top