You need to enable JavaScript to run this app. Django多数据库迁移如何避免在各业务库生成默认系统表
优惠活动
大模型
产品
解决方案
定价
更多

Django多数据库迁移如何避免在各业务库生成默认系统表

问题原因

当前自定义DatabaseRouter的allow_migrate方法仅对lawyer、court、type三个业务应用做了迁移规则限制,对于Django内置的系统应用(如auth、contenttypes、sessions、admin等),方法返回了None。Django的数据库路由规则中,若allow_migrate返回None,会默认允许当前应用迁移到执行命令时指定的数据库中,因此执行业务库迁移时,系统表也会被同步创建到业务库中。

修复方案

修改DatabaseRouter类中的allow_migrate方法,补充系统应用仅允许迁移到default库的规则,修改后的代码如下:

class DatabaseRouter:
    """
    控制所有模型的数据库操作路由
    """
    lawyer_app_labels = {'lawyer'}
    court_app_labels = {'court'}
    type_app_labels = {'type'}

    def db_for_read(self, model, **hints):
        if model._meta.app_label in self.lawyer_app_labels:
            return 'lawyer_db'
        if model._meta.app_label in self.court_app_labels:
            return 'court_db'
        if model._meta.app_label in self.type_app_labels:
            return 'type_db'
        return None

    def db_for_write(self, model, **hints):
        if model._meta.app_label in self.lawyer_app_labels:
            return 'lawyer_db'
        if model._meta.app_label in self.court_app_labels:
            return 'court_db'
        if model._meta.app_label in self.type_app_labels:
            return 'type_db'
        return None

    def allow_relation(self, obj1, obj2, **hints):
        if (
                obj1._meta.app_label in self.lawyer_app_labels or
                obj2._meta.app_label in self.lawyer_app_labels
        ):
            return True
        if (
                obj1._meta.app_label in self.court_app_labels or
                obj2._meta.app_label in self.court_app_labels
        ):
            return True
        if (
                obj1._meta.app_label in self.type_app_labels or
                obj2._meta.app_label in self.type_app_labels
        ):
            return True
        return None

    def allow_migrate(self, db, app_label, model_name=None, **hints):
        if app_label in self.lawyer_app_labels:
            return db == 'lawyer_db'
        if app_label in self.court_app_labels:
            return db == 'court_db'
        if app_label in self.type_app_labels:
            return db == 'type_db'
        # 所有其他应用(含Django内置系统应用)仅允许迁移到default库
        return db == 'default'

注意事项

  • 修改路由后,若业务库已经生成了多余的系统表,可以手动删除,也可以执行python manage.py migrate --database=对应业务库别名 zero清空对应业务库的迁移记录后重新执行迁移
  • default库的迁移不需要指定--database参数,直接运行python manage.py migrate即可,所有系统表会仅同步到default库

内容的提问来源于stack exchange,提问作者hamzeh_pm

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.12 18:54:01