每个app使用不同的数据库
1. 配置数据库连接
# settings.py
# DATABASES中必须要有default字段
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'db',
'USER': '',
'PASSWORD': '',
'HOST': "localhost",
'OPTIONS': {'init_command': 'SET default_storage_engine=INNODB;'}
},
'db1': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'db1',
'USER': '',
'PASSWORD': '',
'HOST': "localhost",
'OPTIONS': {'init_command': 'SET default_storage_engine=INNODB;'}
}
}
2. 配置数据库路由
# settings.py
DATABASES_APPS_MAPPING = {
'app1': 'default',
'app2': 'db1',
}
DATABASE_ROUTERS = ['utils.database_router.DatabaseAppsRouter']
3. 数据库路由文件:
from django.conf import settings
class DatabaseAppsRouter(object):
def db_for_read(self, model, **hints):
app_label = model._meta.app_label
if app_label in settings.DATABASES_APPS_MAPPING:
return settings.DATABASES_APPS_MAPPING[app_label]
return None
def db_for_write(self, model, **hints):
app_label = model._meta.app_label
if app_label in settings.DATABASES_APPS_MAPPING:
return settings.DATABASES_APPS_MAPPING[app_label]
return None
至此,使用app1的model会访问default数据库,使用app2的model会访问db1数据库
同一个app下使用不同数据库
只需要在model class中修改app_label的值即可,app_label默认为此model所在app的名称
class Book2(models.Model):
author = models.CharField(max_length=1024, blank=True, null=True)
title = models.CharField(max_length=1024)
class Meta:
app_label = 'db1'