多数据库配置
数据库配置
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
},
'db2': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db2.sqlite3'),
},
}
迁移其他的数据库
python manage.py migrate --database db2
djang读写分离
手动
models.Student.objects.using('db2').all()
obj = models.Student.objects.using('db2').get(name='zhazha') # 从db2读取
obj.name = 'star'
obj.save(using='default') # 写入default数据库
自动
settings.py
DATABASE_ROUTERS = ['myrouter.Router']
在myrouter.py中写代码
一主一从
class Router:
"""
读写分离
"""
def db_for_write(self, model, **kwargs):
return 'db2'
def db_for_read(self, model, **kwargs):
return 'default'
一主多从
class Router:
"""
一主多从
"""
def db_for_write(self, model, **kwargs):
return 'db1'
def db_for_read(self, model, **kwargs):
return random.choices['db2', 'db3', 'db4']
分库分表
class Router:
"""
分库分表
app01 model db1
app02 model db2
"""
def db_for_write(self, model, **kwargs):
app_name = model._meta.app_label
if app_name == 'app01':
return 'db1'
elif app_name == 'app02':
return 'db2'
def db_for_read(self, model, **kwargs):
app_name = model._meta.app_label
if app_name == 'app01':
return 'db1'
elif app_name == 'app02':
return 'db2'