I've got a nice database I've created in Django, and I'd like to interface with it through some python scripts outside of my website stuff. 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 useful results for this.
12 Answers
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.

- 74,300
- 25
- 125
- 131
-
I have a connector(package) to connect to Hive database, and I'm able to import it in a python program and fetch the data from the Hive database. Where do I place that connector, i.e., in which folder do I place and what do I name my DATABASE_ENGINE ? Thanks In Advance. – Thirumalreddy_Bandi Jun 07 '16 at 11:03
-
What libs do we need to add to requirements.txt to get this? – Pratik Khadloya Feb 27 '18 at 18:25
-
1Am running into an error which i have documented here https://stackoverflow.com/questions/49015994/django-model-outside-of-django – Pratik Khadloya Feb 27 '18 at 18:55
-
Wouldn't it be enough to just import the `settings.py` with all this, which is already existing in the project? – Daniel W. Jun 22 '19 at 13:48
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()

- 5,604
- 6
- 36
- 52
Update setup_environ is to be removed in django 1.6
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

- 31,814
- 10
- 56
- 62
-
3
-
See my follow-up question for alternatives: http://stackoverflow.com/questions/15048963/alternative-to-the-deprecated-setup-environ-for-one-off-django-scripts – B Robster Feb 25 '13 at 18:43
I was looking for answers for django 3.0 and none of the above method exactly worked for me.
I read the official docs at https://docs.djangoproject.com/en/3.0/topics/settings/ and this scripts worked for me.
Project Structure
mysite
mysite
...
settings.py
db.sqlite3
db_tasks.py
manage.py
polls
db_tasks.py:
import os
import django
os.environ['DJANGO_SETTINGS_MODULE'] = 'mysite.settings'
django.setup()
from polls.models import Question
print(Question.objects.all())
out: <QuerySet [<Question: WTU?]>

- 10,830
- 4
- 53
- 88
-
this one helped me. But I think author's environ setup has the wrong value: instead of 'dashboard.settings', it should have been 'mysite.settings' – wr200m Mar 02 '21 at 21:20
-
Name of my project was `dashboard`. You can select whatever you name your project happens to be. – Rahul Dec 22 '21 at 03:50
-
it seems not working on my end. When I ran `python db_task.py` I got an error message `ModuleNotFoundError: No module named 'project_name'` Any additional inputs? – codecumber Mar 22 '22 at 07:44
A final option no-one's mentioned: a custom ./manage.py
subcommand.

- 43
- 6

- 588,541
- 66
- 880
- 895
-
1
-
1Updated link to documentation: https://docs.djangoproject.com/en/dev/howto/custom-management-commands/ – Gary Feb 27 '14 at 19:27
Here is the code I use. Just replace your_project
with your Django project name, yourApp
with your Django app name, any_model
with the model you want to use in models file and any_fild
with the field you want to get from the database:
from django.conf import settings
import django
from your_project.settings import DATABASES, INSTALLED_APPS
settings.configure(DATABASES=DATABASES, INSTALLED_APPS=INSTALLED_APPS)
django.setup()
from yourApp.models import *
print(any_model.objects.all()[0].any_fild)

- 3,304
- 3
- 18
- 41

- 161
- 2
- 5
-
just replace "your_project" with your django project name, "yourApp" with your django app name, "any_model" with model you want to use in models file and "any_fild" with field you want to get from database – Mahdi Heidari kia Sep 30 '18 at 18:09
For django 1.5 on (multiple databases are supported) the DATABASE settings 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'
)

- 39
- 1
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'

- 28,823
- 42
- 111
- 133
-
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 Feb 01 '10 at 22:33
-
This is a very good approach, not duplicating the settings as opposed to the accepted answer. Also, if the Django settings already contain the absolute path to the SQLite file, which is the case **with current Django versions**, then **step 3 is not required anymore**. Making it the most compact solution. – Ad N Oct 03 '15 at 09:07
import os, sys
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "project_name.settings")
sys.path.append(os.path.abspath(os.path.join(BASE_DIR, os.pardir)))
from django.core.wsgi import get_wsgi_application
application = get_wsgi_application()
from app.models import MyModel

- 71
- 1
- 6
Based on the answer by Hai Hu, here is a working script, tested on Django 1.10 and 1.11. I first import Django's base apps because they are needed in many other apps.
import os
from django.conf import settings
from django.apps import apps
conf = {
'INSTALLED_APPS': [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.messages',
'django.contrib.sessions',
'django.contrib.sitemaps',
'django.contrib.sites',
'django.contrib.staticfiles',
'<your_app>',
],
'DATABASES': {
'default': {
'ENGINE': os.environ.get('DB_ENGINE'),
'NAME': os.environ.get('DB_NAME'),
'USER': os.environ.get('DB_USER'),
'PASSWORD': os.environ.get('DB_PASSWORD'),
'HOST': os.environ.get('DB_HOST'),
'PORT': os.environ.get('DB_PORT'),
}
},
'TIME_ZONE': 'UTC'
}
settings.configure(**conf)
apps.populate(settings.INSTALLED_APPS)
<import your app models here>

- 6,424
- 1
- 23
- 31
-
Your solution works. Note: The python file in which you will be pasting this code should be alongside other apps of your project. Or else it would through a bunch of errors. – Gru Apr 16 '19 at 16:57
In Django >= V.3.2.3 Put the following before you model import
import os
import django
os.environ.setdefault(
'DJANGO_SETTINGS_MODULE', 'mymodule.settings'
)
django.setup()
from app.models import MyModel
Then use your model as usual.
myitem = MyModel()
myitem.data = 'some data'
myitem.save()
Regards
for django 3+ :
#########################
directory and files structure:
--my_project
----my_project > settings.py
----myapps
##########################
import sys
sys.path.append("C:/Users/khder/Desktop/test/my_project") #append your main project directory path
import os
import django
#define your setting file as the following.
os.environ.setdefault(
'DJANGO_SETTINGS_MODULE', 'my_project.settings'
)
django.setup()
from my_app.models import MyModel
qs = MyModel.objects.all()
print(qs)
note: for path always use slash '/' not backslash '' even if you are using windows.
this is just example and change it based on your case/requirement.
i hope this helpful . done.

- 1,399
- 12
- 24