I would like to connect my application to 3 different databases.
To do this, I've changed the following code in the settings file:
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'local_db',
'USER': 'root',
'PASSWORD': 'password1',
'HOST': 'localhost',
'PORT': '3306',
'OPTIONS': { 'sql_mode': 'traditional', }
},
'firstExternalDb': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'firstExternalDb',
'USER': 'userName',
'PASSWORD': 'password1',
'HOST': 'firstExternalDb.node.com',
'PORT': '3306',
'OPTIONS': { 'sql_mode': 'traditional', }
},
'secondExternalDb': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'secondExternalDb',
'USER': 'userName',
'PASSWORD': 'password1',
'HOST': 'secondExternalDb.node.com',
'PORT': '3306',
'OPTIONS': { 'sql_mode': 'traditional', }
},
}
And I want to have a possibility to specify for which database I will create a datatable. For example all django tables like 'auth_group' , 'django_admin_log' I want to save in localhost.
Was trying to create a router going through this tutorial https://docs.djangoproject.com/pl/1.11/topics/db/multi-db/#topics-db-multi-db-routing
But I do not understand this. Could you answer my questions:
- Should I create new router for each application ?
- how to define that all django tables should be used by default database ?
I've created two routers inside two models file: The first one only for default DB:
class defaultRouter:
def db_for_read(self, model, **hints):
return 'default'
def db_for_write(self, model, **hints):
return 'default'
def allow_relation(self, obj1, obj2, **hints):
db_list = ('default')
if obj1._state.db in db_list and obj2._state.db in db_list:
return True
return None
def allow_migrate(self, db, app_label, model_name=None, **hints):
return True
And the second one inside the next app:
class secondExternalDbRouter:
def db_for_read(self, model, **hints):
return 'secondExternalDb'
def db_for_write(self, model, **hints):
return 'secondExternalDb'
def allow_relation(self, obj1, obj2, **hints):
db_list = ('secondExternalDb')
if obj1._state.db in db_list and obj2._state.db in db_list:
return True
return None
def allow_migrate(self, db, app_label, model_name=None, **hints):
return True
Both routers are right under the model class, in the same file.
Settings file:
DATABASE_ROUTERS = ['mainApp.models.defaultRouter','secondApp.models.secondExternalDbRouter',]