自定义数据库路由器:实现多租户读写分离
通过 Django 的 DATABASE_ROUTERS 机制,编写自定义路由器实现按租户(tenant)自动选择数据库,并支持主从读写分离。 · 难度:入门 · +10XP
自定义数据库路由器:实现多租户读写分离
多数教程只教你配置多个数据库,但流量分配仍是手动的。本教程深入 db_for_read/db_for_write 方法,结合中间件解析请求中的租户 ID(如子域名或请求头),动态返回不同的数据库别名。同时利用 allow_migrate 阻止租户迁移到公共库。最终实现:每个租户的数据物理隔离,主库写、从库读自动切换。
class TenantRouter:
def db_for_read(self, model, **hints):
tenant_id = hints.get('tenant_id')
if tenant_id:
return f'tenant_{tenant_id}'
return 'default'
def db_for_write(self, model, **hints):
return 'default'
def allow_migrate(self, db, app_label, model_name=None, **hints):
if db.startswith('tenant_'):
return False
return True