91

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 12

82

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.

4
  • 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. Jun 7, 2016 at 11:03
  • What libs do we need to add to requirements.txt to get this? Feb 27, 2018 at 18:25
  • 1
    Am running into an error which i have documented here stackoverflow.com/questions/49015994/… Feb 27, 2018 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, 2019 at 13:48
19

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()
11

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
2
11

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?]>
3
  • 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 2, 2021 at 21:20
  • Name of my project was dashboard. You can select whatever you name your project happens to be.
    – Rahul
    Dec 22, 2021 at 3: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, 2022 at 7:44
9

A final option no-one's mentioned: a custom ./manage.py subcommand.

2
9

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)
1
  • 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 Sep 30, 2018 at 18:09
3

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'
2
  • 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 1, 2010 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 3, 2015 at 9:07
3

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'
)
3
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
0
2

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>
1
  • 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, 2019 at 16:57
1

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

0

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.