Cannot import models from another app in Django

darkhorse picture darkhorse · May 8, 2017 · Viewed 28.6k times · Source

so I have 2 apps running in the same project.

My files are structured as follows:

/project_codebase
    /project
        __init.py
        settings.py
        urls.py
        wsgi.py
        ...    
    /app1
        ...
    /app2
        ...
    manage.py

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:

INSTALLED_APPS = [
    ...

    'app1',
    'app2',
]

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?

Answer

jojo picture jojo · May 8, 2017

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:

from django.apps import apps
MyModel1 = apps.get_model('app1', 'MyModel1')

For earlier django versions (<1.7):

from django.db.models.loading import get_model
MyModel1 = get_model('app1', 'MyModel1')

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:

# in app2.py
class MyModel2(models.Model):
   mymodel1 = models.ForeignKey('app1.MyModel1')

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.