以下是您需要执行的操作才能开始。
- 更新您要使用的数据库的设置。
settings.py
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': '/var/db/projectdb'
}
'db_app1': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': '/var/db/app1db'
}
'db_app2': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': '/var/db/app2db'
}
- 对于每个数据库,实现一个数据库路由器,以适当地路由查询。根据您的情况,在每个应用程序中实施。请注意,这或多或少取自 django 文档。
dbRouter.py
(放置在“app1”文件夹中):
# DB router for app1
class App1DBRouter(object):
"""
A router to control db operations
"""
route_app_labels = {'app1'}
db_name = 'db_app1'
def db_for_read(self, model, **hints):
"""
Attempts to read auth and contenttypes models go to self.db_name.
"""
if model._meta.app_label in self.route_app_labels:
return self.db_name
return None
def db_for_write(self, model, **hints):
"""
Attempts to write auth and contenttypes models go to self.db_name.
"""
if model._meta.app_label in self.route_app_labels:
return self.db_name
return None
def allow_relation(self, obj1, obj2, **hints):
"""
Allow relations if a model in the auth or contenttypes apps is
involved.
"""
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):
"""
Make sure the auth and contenttypes apps only appear in the
self.db_name database.
"""
if app_label in self.route_app_labels:
return db == self.db_name
return None
- Update
DATABASE_ROUTERS
在设置.py
settings.py
DATABASE_ROUTERS = ['app1.dbRouter.App1DBRouter', 'app2.dbRouter.App2DBRouter']