在一個Django應(yīng)用中可以創(chuàng)建多個APP應(yīng)用雳灵,每個APP應(yīng)用都可以獨立使用幢痘,在有多個APP的情況下介杆,APP之間若數(shù)據(jù)庫使用不一褥符,如APP1使用的數(shù)據(jù)庫IP與APP2使用的數(shù)據(jù)庫IP不一致龙誊,或者APP1使用MYSQL,APP2使用PGSQL喷楣,那么就要對不同APP的數(shù)據(jù)庫進行不同的設(shè)置趟大。
以下為一次實際操作演示。
DATABASES?={
????'default':?{
????????'ENGINE':?'django.db.backends.sqlite3',
????????'NAME':?os.path.join(BASE_DIR,?'db.sqlite3'),
????},
????'db1':?{
????????'ENGINE':?'django.db.backends.mysql',
????????'NAME':?'dbname1',
????????'USER':?'your_db_user_name',
????????'PASSWORD':?'yourpassword',
????????"HOST":?"localhost",
????},
????'db2':?{
????????'ENGINE':?'django.db.backends.mysql',
????????'NAME':?'dbname2',
????????'USER':?'your_db_user_name',
????????'PASSWORD':?'yourpassword',
????????"HOST":?"localhost",
????},
}
#?use?multi-database?in?django
#?add?by?WeizhongTu
DATABASE_ROUTERS?=['{項目名稱}.database_router.DatabaseAppsRouter']
DATABASE_APPS_MAPPING?={
????#?example:
????#'app_name':'database_name',
????'app1':?'db1',
????'app2':?'db2',
}
在project_name目錄下創(chuàng)建一個database_route.py文件(即與setting.py同級的文件)
文件中寫入:
? ??fromdjango.conf?importsettings
DATABASE_MAPPING?=settings.DATABASE_APPS_MAPPING
classDatabaseAppsRouter(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'}
????"""
????defdb_for_read(self,?model,?**hints):
????????""""Point?all?read?operations?to?the?specific?database."""
????????ifmodel._meta.app_label?inDATABASE_MAPPING:
????????????return DATABASE_MAPPING[model._meta.app_label]
????????return None
????defdb_for_write(self,?model,?**hints):
????????"""Point?all?write?operations?to?the?specific?database."""
????????ifmodel._meta.app_label?inDATABASE_MAPPING:
????????????return DATABASE_MAPPING[model._meta.app_label]
????????return None
????defallow_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)
????????ifdb_obj1?anddb_obj2:
????????????ifdb_obj1?==db_obj2:
????????????????return True
????????????else:
????????????????return False
????????return None
實際操作時:
python manage.py makemigrations {app} 創(chuàng)建存儲
python manage.py migrate? 同步數(shù)據(jù)庫? ? ?
在代碼中使用時候:
test=BlogT.objects.using('db1').get_or_create(title=title,content=content)
在object取得對象時候指定你使用的數(shù)據(jù)庫 using(‘{setting的數(shù)據(jù)庫}’)