Following this guide, I am able to use models outside of Django with the following file structure by calling python main.py
.
├── data
│ ├── __init__.py
│ ├── migrations
│ │ └── __init__.py
│ └── models.py
├── main.py
├── manage.py
└── settings.py
where main.py looks like this:
import os, django
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'settings')
django.setup()
from data.models import Foo, Bar #...
print(Foo.objects.all()) #this works fine
What I want to do is turn this into a "package" called db
that looks like this:
├── data
│ ├── __init__.py
│ ├── migrations
│ │ └── __init__.py
│ └── models.py
├── __init__.py
├── manage.py
└── settings.py
And in the __init__.py
of the db
package, I want to do this:
import os, django
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'settings')
django.setup()
from data.models import Foo, Bar # ...
from django.db import connection
__all__ = [
'connection',
'Foo',
'Bar',
#...
]
So I can call the db
package from test.py
(which is in the same directory as db
) like this:
import db
print(db.Foo.objects.all()) # this throws an error "no module named data"
or like this:
from db import Foo
print(Foo.objects.all()) # this throws an error "no module named settings"
Is there a way I can use Django's models without having to call:
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'settings')
django.setup()
on every page that uses a model?
What am I missing here?