Skip to main content

Django ImportError:cannot import name from partially initialized module (problem of circular import of models between different apps)

background:

There are two apps that refer to each other's models.py models as foreign keys. Models.py in app1 refers to model B of app2, and models.py in app2 refers to model A of app1.

Wrong spelling:

# Writing like this will result in errors: Django ImportError:cannot import name '...' from partially initialized module'...' (most likely due to a circular import)

# app1的models.py
from app2.models import B

class L1(models.Model):
b = models.ForeignKey(B, on_delete=models.CASCADE)

# app2的models.py
from app1.models import A

class L2(models.Model):
a = models.ForeignKey(A, on_delete=models.CASCADE)

The correct way to write it is to use a string reference

# AppName must be the name of the app registered in settings. py, directly following it. The model name can be referenced
# Models. py for app1
# Cannot reference from app2. models import B on the outermost layer

class L1(models.Model):
b = models.ForeignKey("app_name.B", on_delete=models.CASCADE)

# Models. py for app2
# Cannot reference from app1. models import A on the outermost layer

class L2(models.Model):
a = models.ForeignKey("app_name.A", on_delete=models.CASCADE)