在项目中我们每个app对应不同的数据库,其中有一个是从数据库逆向生成model,做个笔记。
- 修改项目的setting.py配置 :
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql', # 默认用mysql
'NAME': 'bk', # 数据库名 (默认与APP_ID相同)
'USER': 'root', # 你的数据库user
'PASSWORD': 'root', # 你的数据库password
'HOST': 'xxx.xxx.xxx.xxx', # 开发的时候,使用localhost
'PORT': '3306', # 默认3306
},
'cloudsino_test': {
'ENGINE': 'django.db.backends.mysql', # 默认用mysql
'NAME': 'cloudsino_test', # 数据库名 (默认与APP_ID相同)
'USER': 'root', # 你的数据库user
'PASSWORD': 'root', # 你的数据库password
'HOST': 'xxx.xxx.xxx.xxx', # 开发的时候,使用localhost
'PORT': '3306', # 默认3306
},
}
# 设置数据库的路由规则方法
DATABASE_ROUTERS = ['conf.database_router.DatabaseAppsRouter']
# 设置APP对应的数据库路由表,哪个app要连接哪个数据库,没有指定会用default那个。
DATABASE_APPS_MAPPING = {
# example:
#'app_name':'database_name',
'home_application': 'cloudsino_test',
'cmdb': 'default',
}
- 新建database_router.py:
在与setting.py文件同级的目录下新建database_router.py文件:
# -*- coding: utf-8 -*-
from settings_development import DATABASE_APPS_MAPPING
DATABASE_MAPPING = DATABASE_APPS_MAPPING
class DatabaseAppsRouter(object):
def db_for_read(self, model, **hints):
""""建议model类型对象从哪一个数据库读取."""
if model._meta.app_label in DATABASE_MAPPING:
return DATABASE_MAPPING[model._meta.app_label]
return None
def db_for_write(self, model, **hints):
"""建议model类型对象的写入操作应该使用哪个数据库"""
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.
如果obj1 和obj2 之间应该允许关联则返回True,如果应该防止关联则返回False,如果路由无法判断则返回None
"""
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_syncdb(self, db, model):
"""Make sure that apps only appear in the related database."""
if db in DATABASE_MAPPING.values():
return DATABASE_MAPPING.get(model._meta.app_label) == db
elif model._meta.app_label in DATABASE_MAPPING:
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.
定义迁移操作是否允许在别名为db的数据库上运行。如果操作应该运行则返回Tru