Skip to content

Instantly share code, notes, and snippets.

@zh012
Created April 23, 2015 19:54
Show Gist options
  • Select an option

  • Save zh012/c624b5dfd8ef1cd57194 to your computer and use it in GitHub Desktop.

Select an option

Save zh012/c624b5dfd8ef1cd57194 to your computer and use it in GitHub Desktop.
Django ORM standalone by hbdgaf@stackoverflow

Using django ORM without a settings file. Here's how:

In the stand-alone app launcher file:

from django.conf import settings
from django.core.management import execute_from_command_line

#Django settings
settings.configure(DEBUG=False,
    DATABASES = {
        'default': {
            'ENGINE': 'django.db.backends.sqlite3',
            'NAME': '/path/to/dbfile',
            'USER': '',
            'PASSWORD': '',
            'HOST': '',
            'PORT': '',
        }
    },
    INSTALLED_APPS = ('modelsapp',)
)

if not os.path.exists('/path/to/dbfile'):
    sync = ['manage.py', 'syncdb']
    execute_from_command_line(sync)

Now you just need a ./modelsapp folder containing an __init__.py and a models.py. The config uses sqlite for simplicity sake, but it could use any of the db backends.

Folder structure:

./launcher.py
./modelsapp
    __init__.py
    models.py

Note that you don't have to have a manage.py proper. The import execute_from_command_line just finds it.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment