Django Multi Database

January 20, 2011

Django allows you to connect to multiple databases.

Definition

Replace the existing database connection details in settings.py with

DATABASES = {
  'default' : {
    'NAME': 'wamdev',
    'ENGINE': 'django.db.backends.postgresql_psycopg2',
    'USER': 'user',
    'PASSWORD': 'password',
    'HOST' : 'server',
    'PORT' : '5432',
  },
  'integration': {
    'NAME': 'INT',
    'ENGINE': 'django.db.backends.oracle',
    'USER': 'user',
    'PASSWORD': 'password',
    'HOST' : 'server',
    'PORT' : '1521',
  },
  'impact': {
    'NAME': 'IMPACT',
    'ENGINE': 'django.db.backends.oracle',
    'USER': 'user',
    'PASSWORD': 'password',
    'HOST' : 'server',
    'PORT' : '1521',
  }
}

Django ORM

The django ORM will use the default database unless told otherwise.

To specify a different one, use using:

lGroup = Group.objects.using('integration').filter(id=pSerial)[0]

Raw SQL

Raw SQL will use the default database unless told otherwise. To use a different one:

from django.db import connections

lCursor = connections['impact'].cursor()

References