Django 读写分离

Posted by luoruiqing on July 25, 2020

db_router.py 创建该文件到项目(主APP)目录下

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class DBRouter:

    db_list = ('DB_WRITER', 'DB_READER', 'DB_ROOT')  # 主从库

    def db_for_read(self, model, **hints):
        ''' 读取选择库 '''
        return 'DB_READER'

    def db_for_write(self, model, **hints):
        ''' 写入选择库 '''
        return 'DB_WRITER'

    def allow_relation(self, obj1, obj2, **hints):
        ''' 允许数据库池中的两个对象间的任何关系 '''
        return True

    def allow_migrate(self, db, app_label, model_name=None, **hints):
        ''' 迁移指定库 (不使用) '''
        return 'DB_ROOT'

settings.py 配置文件

1
2
# 格式 <路由文件>.<类名>
DATABASE_ROUTERS = ['db_router.DBRouter']