在django項目中, 一個工程中存在多個APP應用很常見. 有時候希望不同的APP連接不同的數據庫,這個時候需要建立多個數據庫連接。
1. 修改項目的 settings 配置
在 settings.py 中配置需要連接的多個數據庫連接串
DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'sqlite3'), }, 'db01': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db_01'), }, 'db02': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db_02'), },}
假設現在我們用到3個數據庫,一個default默認庫,一個 db01 和 db02
2. 設置數據庫的路由規則方法
在 settings.py 中配置 DATABASE_ROUTERS
DATABASE_ROUTERS = ['Prject.database_router.DatabaseAppsRouter']
Project: 建立的django項目名稱(project_name)
database_router: 定義路由規則database_router.py 文件名稱, 這個文件名可以自己定義
DatabaseAppsRouter: 路由規則的類名稱,這個類是在database_router.py 文件中定義
3. 設置APP對應的數據庫路由表
每個APP要連接哪個數據庫,需要在做匹配設置,在 settings.py 文件中做如下配置:
DATABASE_APPS_MAPPING = { # example: # 'app_name':'database_name', 'app02': 'db02', 'app01': 'db01', 'admin': 'db01', 'auth': 'db01', 'contenttypes': 'db01', 'sessions': 'db01',}
以上的app01, app02是項目中的 APP名,分別指定到 db01, db02 的數據庫。
為了使django自己的表也創建到你自己定義的數據庫中,你可以指定 : admin, auth, contenttypes, sessions 到設定的數據庫中,如果不指定則會自動創建到默認(default)的數據庫中
4. 創建數據庫路由規則
在項目工程根路徑下(與 settings.py 文件一級)創建 database_router.py 文件:
from django.conf import settingsDATABASE_MAPPING = settings.DATABASE_APPS_MAPPINGclass DatabaseAppsRouter(object): """ A router to control all database operations on models for different databases. In case an app is not set in settings.DATABASE_APPS_MAPPING, the router will fallback to the `default` database. Settings example: DATABASE_APPS_MAPPING = {'app1': 'db1', 'app2': 'db2'} """ def db_for_read(self, model, **hints): """"Point all read operations to the specific database.""" if model._meta.app_label in DATABASE_MAPPING: return DATABASE_MAPPING[model._meta.app_label] return None def db_for_write(self, model, **hints): """Point all write operations to the specific database.""" if model._meta.app_label in DATABASE_MAPPING: return DATABASE_MAPPING[model._meta.app_label] return None def allow_relation(self, obj1, obj2, **hints): """Allow any relation between apps that use the same database.""" db_obj1 = DATABASE_MAPPING.get(obj1._meta.app_label) db_obj2 = DATABASE_MAPPING.get(obj2._meta.app_label) if db_obj1 and db_obj2: if db_obj1 == db_obj2: return True else: return False return None def allow_syncdb(self, db, model): """Make sure that apps only appear in the related database.""" if db in DATABASE_MAPPING.values(): return DATABASE_MAPPING.get(model._meta.app_label) == db elif model._meta.app_label in DATABASE_MAPPING: return False return None def allow_migrate(self, db, app_label, model=None, **hints): """ Make sure the auth app only appears in the 'auth_db' database. """ if db in DATABASE_MAPPING.values(): return DATABASE_MAPPING.get(app_label) == db elif app_label in DATABASE_MAPPING: return False return None
新聞熱點
疑難解答