要在Django中使用多个数据库,只需在中指定每个数据库settings.py:
DATABASES = { 'default': { 'NAME': 'app_data', 'ENGINE': 'django.db.backends.postgresql', 'USER': 'django_db_user', 'PASSWORD': os.environ['LOCAL_DB_PASSWORD'] }, 'users': { 'NAME': 'remote_data', 'ENGINE': 'django.db.backends.mysql', 'HOST': 'remote.host.db', 'USER': 'remote_user', 'PASSWORD': os.environ['REMOTE_DB_PASSWORD'] } }
使用dbrouters.py文件来指定对于每种数据库操作类,哪些模型应在哪些数据库上进行操作,例如,对于存储在中的远程数据remote_data,您可能需要以下内容:
class DbRouter(object): """ A router to control all database operations on models in the auth application. """ def db_for_read(self, model, **hints): """ Attempts to read remote models go to remote database. """ if model._meta.app_label == 'remote': return 'remote_data' return 'app_data' def db_for_write(self, model, **hints): """ Attempts to write remote models go to the remote database. """ if model._meta.app_label == 'remote': return 'remote_data' return 'app_data' def allow_relation(self, obj1, obj2, **hints): """ Do not allow relations involving the remote database """ if obj1._meta.app_label == 'remote' or \ obj2._meta.app_label == 'remote': return False return None def allow_migrate(self, db, app_label, model_name=None, **hints): """ Do not allow migrations on the remote database """ if model._meta.app_label == 'remote': return False return True
最后,将您添加dbrouter.py到settings.py:
DATABASE_ROUTERS = ['path.to.DbRouter', ]