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?
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.
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".
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With