django 数据库相关配置
I.读写分离
1.手动分库的写法
配置多个数据库
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
视图函数中进行orm操作时,可以指定数据库
# Create your views here.
def index(request, *args):
obj = models.Student.objects.using('deafult').get(pk=3)
obj2 = models.Student.objects.using('db2').create(name='xxx',class='1')
return render(request, 'index.html',{'time':time.time()})
2.自动分库的写法
settings.py中配置
DATABASE_ROUTERS = ['myrouter.Router']
新建一个myrouter.py文件
class Router:
def db_for_read(self, model, **kwargs):
return 'default'
def db_for_write(self, model, **kwargs):
return 'db2'
此时在视图函数中就不用手动指定库名了
II.一主多从的配置
要求一个库中写入,多个库中读取
myrouter.py中
import random
class Router:
"""
一主多从
"""
def db_for_read(self, model, **kwargs):
return random.choice(['db1', 'db2', 'db3']) # 这是自己做的逻辑,还可以加权重
def db_for_write(self, model, **kwargs):
return 'default'
III.分库分表的配置
class Router:
"""
分库分表
app01的操作 default
app02的操作 db2
"""
def db_for_read(self, model, **kwargs):
if model._meta.app_label == 'app01':
return 'default'
elif model._meta.app_label == 'app02':
return 'db2'
def db_for_write(self, model, **kwargs):
if model._meta.app_label == 'app01':
return 'default'
elif model._meta.app_label == 'app02':
return 'db2'
来源:https://www.cnblogs.com/robertx/p/11093989.html