32
loading...
This website collects cookies to deliver better user experience
settings.py
snippet defining two databases – a default PostgreSQL database and a MySQL database called users_db:DATABASES = {
'default': {
'NAME': 'app_data',
'ENGINE': 'django.db.backends.postgresql',
'USER': 'postgres_user',
'PASSWORD': 's3krit'
},
'users_db': {
'NAME': 'user_data',
'ENGINE': 'django.db.backends.mysql',
'USER': 'mysql_user',
'PASSWORD': 'priv4te'
}
}
DATABASES = {
'default': {},
'users': {
'NAME': 'user_data',
'ENGINE': 'django.db.backends.mysql',
'USER': 'mysql_user',
'PASSWORD': 'superS3cret'
},
'customers': {
'NAME': 'customer_data',
'ENGINE': 'django.db.backends.mysql',
'USER': 'mysql_cust',
'PASSWORD': 'veryPriv@ate'
}
}
$ ./manage.py migrate
$ ./manage.py migrate --database=users
$ ./manage.py migrate --database=users
$ ./manage.py migrate --database=customers
db_routers.py
db_routers.py
file:
class AuthRouter:
route_app_labels = {'auth', 'contenttypes'}
def db_for_read(self, model, **hints):
if model._meta.app_label in self.route_app_labels:
return 'auth_db'
return None
def db_for_write(self, model, **hints):
if model._meta.app_label in self.route_app_labels:
return 'auth_db'
return None
def allow_relation(self, obj1, obj2, **hints):
if (
obj1._meta.app_label in self.route_app_labels or
obj2._meta.app_label in self.route_app_labels
):
return True
return None
def allow_migrate(self, db, app_label, model_name=None, **hints):
if app_label in self.route_app_labels:
return db == 'auth_db'
return None
class UsersRouter:
route_app_labels = {'users', 'accounts'}
def db_for_read(self, model, **hints):
if model._meta.app_label in self.route_app_labels:
return 'users_db'
return None
def db_for_write(self, model, **hints):
if model._meta.app_label in self.route_app_labels:
return 'users_db'
return None
def allow_migrate(self, db, app_label, model_name=None, **hints):
if app_label in self.route_app_labels:
return db == 'users_db'
return None
route_app_labels
then it returns and uses the selected database. In this case, only the users and accounts apps can access the users_db database as it is specified in route_app_labels
.db_for_read(model, **hints)
db_for_write(model, hints)
allow_relation(obj1, obj2, **hints)
allow_migrate(db, app_label, model_name=None, **hints)
DATABASE_ROUTERS = ['path.to.AuthRouter', 'path.to.UsersRouter']
>>> # This will run on the 'default' database.
>>> Publisher.objects.all()
>>> # So will this.
>>> Publisher.objects.using('default').all()
>>> # This will run on the 'users' database.
>>> Publisher.objects.using('users').all()