Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot import models from another app in Django

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?

like image 778
darkhorse Avatar asked May 08 '17 12:05

darkhorse


People also ask

How import all models in Django?

To do this, create a directory called /«project»/«app_name»/models , inside it put __init__.py (to declare it as a module) and then create your files inside there. You then need to import your file contents into the module in __init__.py . You should read about Python modules to understand this.

What is PK in Django model?

pk is short for primary key, which is a unique identifier for each record in a database. Every Django model has a field which serves as its primary key, and whatever other name it has, it can also be referred to as "pk".


1 Answers

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.

like image 161
jojo Avatar answered Sep 23 '22 19:09

jojo