Using Django database layer outside of Django?


Question

I've got a nice database I've created in Django, and I'd like to interface with through some python scripts outside of my website stuff, so I'm curious if it's possible to use the Django database API outside of a Django site, and if so does anyone have any info on how it can be done? Google hasn't yielded many hits for this.

1
64
2/1/2010 10:05:31 PM

Accepted Answer

You just need to configure the Django settings before you do any calls, including importing your models. Something like this:

from django.conf import settings
settings.configure(
    DATABASE_ENGINE = 'postgresql_psycopg2',
    DATABASE_NAME = 'db_name',
    DATABASE_USER = 'db_user',
    DATABASE_PASSWORD = 'db_pass',
    DATABASE_HOST = 'localhost',
    DATABASE_PORT = '5432',
    TIME_ZONE = 'America/New_York',
)

Again, be sure to run that code before running, e.g.:

from your_app.models import *

Then just use the DB API as usual.

62
2/1/2010 10:08:14 PM

For django 1.7, I used the following to get up and running.

settings.py:

from django.conf import settings
settings.configure(
    DATABASES={
        'default': {
            'ENGINE': 'django.db.backends.postgresql_psycopg2',
            'NAME': 'name',
            'USER': 'usr',
            'PASSWORD': 'secret',
            'HOST': '127.0.0.1',
            'PORT': '5432',
        },
    },
    TIME_ZONE='America/Montreal',
)

In the file containing the startup routine

import os
import django

import v10consolidator.settings
from myapp.models import *

os.environ.setdefault(
    "DJANGO_SETTINGS_MODULE",
    "myapp.settings"
)
django.setup()

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon