当前位置:Gxlcms > 数据库问题 > Django中多数据库的使用

Django中多数据库的使用

时间:2021-07-01 10:21:17 帮助过:8人阅读


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   

人气教程排行