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.
+2
A:
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.
FogleBird
2010-02-01 22:08:14
Most excellent, exactly what I was looking for!
gct
2010-02-01 22:34:21
+1
A:
For using Django ORM from other applications you need:
1) export DJANGO_SETTINGS_MODULE=dproj.settings
2) Add your Django app folder to the path (you can do it in the code of your non-django-app):
sys.path = sys.path + ['/path/to/your/app/']
3) If using SQLite, use the full path to the db file in settings.py:
DATABASE_NAME = '/path/to/your/app/base.db'
Juanjo Conti
2010-02-01 22:18:32
As a hacky alternative to setting the environment variable properly, you can put os.environ['DJANGO_SETTINGS_MODULE']=dproj.settings at the top before importing your application modules. That only changes DJANGO_SETTINGS_MODULE for the duration of that process.
twneale
2010-02-01 22:33:51
+4
A:
If you're able to import your settings.py file, then take a look at handy setup_environ command.
from django.core.management import setup_environ
from mysite import settings
setup_environ(settings)
#here you can do everything you could in your project
Dmitry Shevchenko
2010-02-01 22:19:03
+1
A:
A final option no-one's mentioned: a custom ./manage.py
subcommand.
Daniel Roseman
2010-02-01 22:55:08