Using a Django database layer outside of Django?

I have a nice database that I created in Django, and I would like to interact with some python scripts outside of my website, so I'm curious if the Django database APIs can be used outside of the Django website, and if it has any information on how to do this? Google did not give many hits for this.

+51
python django mysql
Feb 01 '10 at 22:05
source share
6 answers

You just need to configure your Django settings before making any calls, including importing your models. Something like that:

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 this code before running, for example:

 from your_app.models import * 

Then just use the DB API as usual.

+52
Feb 01 '10 at
source share
— -

Update setup_environ need to be removed in django 1.6

If you can import the settings.py file, look in the convenient 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 
+12
Feb 01 '10 at
source share

For django 1.7, I used the following to launch and launch.

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 procedure

 import os import django import v10consolidator.settings from myapp.models import * os.environ.setdefault( "DJANGO_SETTINGS_MODULE", "myapp.settings" ) django.setup() 
+11
Oct 29 '14 at 14:45
source share

The last option that no one mentioned: the user subcommand ./manage.py .

+6
Feb 01 '10 at 22:55
source share

For django 1.5 on (multiple databases are supported), the DATABASE settings have also changed. You need to adapt the previous answer to ...

 settings.configure( DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'db_name', 'USER': 'db_usr', 'PASSWORD': 'db_pass', 'HOST': '', 'PORT': '', }, }, TIME_ZONE = 'Europe/Luxembourg' ) 
+3
Aug 07 '13 at 12:35 on
source share

To use Django ORM from other applications you need to:

1) export DJANGO_SETTINGS_MODULE=dproj.settings

2) Add your Django application folder to the path (you can do this in the code of your non-django application):

 sys.path = sys.path + ['/path/to/your/app/'] 

3) If you are using SQLite, use the full path to the db file in settings.py:

 DATABASE_NAME = '/path/to/your/app/base.db' 
+2
Feb 01 2018-10-01T00
source share



All Articles