Django中多数据库的使用
Posted stormztt
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Django中多数据库的使用相关的知识,希望对你有一定的参考价值。
django中,你可以为每一个app都单独设置一个数据库。
一、在项目project下新建文件database_router.py文件:
DATABASE_MAPPING = ‘app1‘: ‘db1‘,‘app2‘:‘db2‘
class DatabaseAppsRouter(object):
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_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
二、settings.py
2.1 数据库配置
DATABASES =
ABASES =
‘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",
,
2.2 router配置
DATABASE_ROUTERS = [‘project_name.database_router.DatabaseAppsRouter‘]
三、使用时数据库同步
python manage.py migrate --database=db1
python manage.py migrate --database=db2
以上是关于Django中多数据库的使用的主要内容,如果未能解决你的问题,请参考以下文章