Reputation: 19259
I copied some manage.py
lines to my __init__.py
and all my views
and models
can be imported from anywhere without requiring python manage.py shell
:
import os
import django
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'myproject.settings')
django.setup()
That way I can import my submodules in __init__.py
(further down):
import glob
modules = glob.glob(os.path.join(os.path.dirname(__file__), '*.py'))
__all__ = [os.path.basename(f)[:-3] for f in modules
if os.path.isfile(f) and not f.endswith('__init__.py')]
from . import *
That way I can do this from any directory:
import myproject as mp
mp.models.MyModel.objects.get(field_name='value')
This is handy when importing data or doing data migrations away from the project fixtures directory.
Is there anything wrong with this? If not, why doesn't Django do it this way by default when you python manage.py startproject
?
Upvotes: 4
Views: 233
Reputation: 15926
id
), how you want to load apps is up to you.django.setup
django would be setup once for each app. This also does not account for multiple threads running in a webserver, and application setup. which might cause resource contention when you don't necessarily want any. Finally, you'd also lose some control of application setup an initialization order in cases where you need it since the order of imports is now alphabetical instead of via INSTALLED_APPS
. Having to write management commands and use them via manage.py seems like a small price to pay for playing well with other apps.Upvotes: 1