03.mysql主从项目实战
# 1.django使用mysql主从
# 1.1 在syl/settings.py中配置mysql主从
# 配置django
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'syl',
'HOST': '127.0.0.1',
'PORT': '3307',
'USER': 'root',
'PASSWORD': '1',
},
'slave': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'syl',
'HOST': '127.0.0.1',
'PORT': '3308',
'USER': 'root',
'PASSWORD': '1',
}
}
# 数据库路由配置
DATABASE_ROUTERS = ['utils.db_router.MasterSlaveDBRouter']
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
# 1.2 编写mysql路由文件
# utils/db_router.py
class MasterSlaveDBRouter(object):
"""数据库读写路由"""
def db_for_read(self, model, **hints):
"""读"""
return "slave"
def db_for_write(self, model, **hints):
"""写"""
return "default"
def allow_relation(self, obj1, obj2, **hints):
"""是否运行关联操作"""
return True
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
2
3
4
5
6
7
8
9
10
11
12
13
14
15
上次更新: 2024/3/13 15:35:10