码迷,mamicode.com
首页 > 数据库 > 详细

Django中多数据库的使用

时间:2019-08-05 18:47:49      阅读:109      评论:0      收藏:0      [点我收藏+]

标签:sqlite   javascrip   values   and   lang   tab   data   配置   _for   

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中多数据库的使用

标签:sqlite   javascrip   values   and   lang   tab   data   配置   _for   

原文地址:https://www.cnblogs.com/stormztt/p/11304756.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!