hobs
hobs

Reputation: 19259

Why do Django apps require `manage.py` for everything instead of using `__init__py`?

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

Answers (1)

2ps
2ps

Reputation: 15926

  1. Is there anything wrong with it? There's nothing wrong with it! Different dev teams have different preferences. While django is notoriously opinionated (e.g., all tables should have a single auto-increment primary key field called id), how you want to load apps is up to you.
  2. Why not do this by default? I can think of a couple of reasons. First, several people have their own reusable apps or there are even pypi available django apps that you can install. If each one of them called 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

Related Questions