Here is what you will have to do to get going.
1) Update settings for databases that you want to use.
settings.py
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': '/var/db/projectdb'
}
'db_app1': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': '/var/db/app1db'
}
'db_app2': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': '/var/db/app2db'
}
2) For each database, implement a database router that will route the queries appropriately. In your case implement in each app. Note this more or less taken from django docs.
app1.dbRouter.py
# DB router for app1
class App1DBRouter(object):
"""
A router to control app1 db operations
"""
def db_for_read(self, model, **hints):
"Point all operations on app1 models to 'db_app1'"
from django.conf import settings
if not settings.DATABASES.has_key('db_app1'):
return None
if model._meta.app_label == 'app1':
return 'db_app1'
return None
def db_for_write(self, model, **hints):
"Point all operations on app1 models to 'db_app1'"
from django.conf import settings
if not settings.DATABASES.has_key('db_app1'):
return None
if model._meta.app_label == 'app1':
return 'db_app1'
return None
def allow_relation(self, obj1, obj2, **hints):
"Allow any relation if a model in app1 is involved"
from django.conf import settings
if not settings.DATABASES.has_key('db_app1'):
return None
if obj1._meta.app_label == 'app1' or obj2._meta.app_label == 'app1':
return True
return None
def allow_syncdb(self, db, model):
"Make sure the app1 app only appears on the 'app1' db"
from django.conf import settings
if not settings.DATABASES.has_key('db_app1'):
return None
if db == 'db_app1':
return model._meta.app_label == 'app1'
elif model._meta.app_label == 'app1':
return False
return None
3) Update DATABASE_ROUTERS
in settings.py
settings.py
DATABASE_ROUTERS = ['app1.dbRouter.App1DBRouter', 'app2.dbRouter.App2DBRouter']
Note for people who use Python 3
statements like
if not settings.DATABASES.has_key('db_app1'):
should become
if 'db_app1' not in settings.DATABASES: