Django: Database Router for Multiple Databases
Aug. 24, 2022
django
Using multiple database in the Django project you may face with situation when you need apply migrations for some app or model just to the some databse instead all of defined databases, or you need to perform read/write actions for models of the some application only for specific database instead specifying .using(db)
every time.
For this purpose use need define and enable database router.
Define database router
This example demonstrates how to restrict read/write/migration operations of the “example_app” models to the “database2” only.
app/dbrouter.py
class ExampleAppDatabaseRouter(object):
def db_for_read(self, model, **hints):
if model._meta.app_label == 'example_app':
return 'database2'
return None
def db_for_write(self, model, **hints):
if model._meta.app_label == 'example_app':
return 'database2'
return None
def allow_migrate(self, db, app_label, model_name=None, **hints):
if app_label == 'example_app':
return db == 'database2'
elif db == 'database2':
return False
settings.py
Specify list of all your defined routers in the settings.py
file.
DATABASE_ROUTERS = [
'app.dbrouter.ExampleAppDatabaseRouter',
]
Restrict defined models to the single database
class ExampleAppDatabaseRouter(object):
def allow_migrate(self, db, app_label, model_name=None, **hints):
if db == 'database2':
if model_name not in ['comments', 'likes']:
return False