Skip to content
Advertisement

Cannot import models from another app in Django

so I have 2 apps running in the same project.

My files are structured as follows:

JavaScript

So, I for some weird reason have a different name for my base directory (that is, it ends with codebase). Hopefully, that is not an issue.

In my settings.py, I have this:

JavaScript

Ok, so in my models.py (from app2), I can easily import models from app1 with from app1.models import *, however, when I use from app2.models import * in my models.py (from app1), I get an ImportError.

Any solutions to this?

Advertisement

Answer

This might be due to circular import issues. To avoid this you should load the model dynamically:

For recent versions of django (1.7+) use the application registry:

JavaScript

For earlier django versions (<1.7):

JavaScript

Note 1: If you want to define a ForeignKey relationship, there is no need for a separate import statement. Django has you covered on this:

If app1 is an installed app, you should define the ForeignKey relationship as follows:

JavaScript

Note 2: The get_model only works if app1 is an installed app and MyModel1 is the model you want to import from app1.

Note 3: Try to avoid wildcard import (from ... import *), as this is bad practice.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement