settings.py:
DATABASES = {
' Default ': {
' ENGINE ': ' Django.db.backends.mysql ', # Add ' postgresql_psycopg2 ', ' MySQL ', ' sqlite3 ' or ' Oracle '.
' NAME ': ' Test ', # Or path to database file if using Sqlite3.
' USER ': ' Test ', # not used with Sqlite3.
' PASSWORD ': ' Test ', # not used with Sqlite3.
' HOST ': ', # Set to empty string for localhost. Not used with Sqlite3.
' PORT ': ' 3306 ', # Set to empty string for default. Not used with Sqlite3.
},
' User ': {
' ENGINE ': ' Django.db.backends.mysql ', # Add ' postgresql_psycopg2 ', ' MySQL ', ' sqlite3 ' or ' Oracle '.
' NAME ': ' UserDB ', # Or path to database file if using Sqlite3.
' User ': ' User ', # used with Sqlite3.
' PASSWORD ': ' User ', # used with Sqlite3.
' HOST ': ' 10.58.**.** ', # Set to empty string for localhost. Not used with Sqlite3.
' PORT ': ' 3306 ', # Set to empty string for default. Not used with Sqlite3.
}
}
Database_routers = [' dbsettings.appdb ']
Implement your own DB routers, which determines which db each application uses
dbsettings.py:
Class Appdb (object):
def db_for_read (self, model, **hints):
#该方法定义读取时从哪一个数据库读取
return Self.__app_router (model)
def db_for_write (self, model, **hints):
#该方法定义写入时从哪一个数据库读取, if read-write separation, can be additional configuration
return Self.__app_router (model)
def allow_relation (self, obj1, Obj2, **hints):
#该方法用于判断传入的obj1和obj2是否允许关联, can be used for many-to-many and foreign keys
#同一个应用同一个数据库
if Obj1._meta.app_label = = Obj2._meta.app_label:
Return True
#User和Essay是允许关联的
Elif Obj1._meta.app_label in (' Userapp ', ' Essayapp ') and
#接上一行 Obj2._meta.app_label in (' Userapp ', ' Essayapp '):
Return True
def allow_syncdb (self, DB, model):
#该方法定义数据库是否能和名为db的数据库同步
return Self.__app_router (model) = = db
#添加一个私有方法用来判断模型属于哪个应用 and return the database that should be used
def __app_router (self, model):
if Model._meta.app_label = = ' user ':
Return ' UserDB '
else:
Return ' Default '