标签: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 Nonedef 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 Nonedef 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 Trueelse:return Falsereturn Nonedef 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) == dbelif app_label in DATABASE_MAPPING:return Falsereturn 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=db1python manage.py migrate --database=db2
标签:sqlite javascrip values and lang tab data 配置 _for
原文地址:https://www.cnblogs.com/stormztt/p/11304756.html