Using Django database layer outside of Django?

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

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

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?]>

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.