You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Django 2.2.9中实现多数据库迁移?

Django 2.2.9 非默认数据库迁移解决方案

1. 配置数据库路由

先在项目中创建routers.py文件,定义路由类,明确哪些模型对应哪个非默认数据库:

class App1Router:
    def db_for_read(self, model, **hints):
        if model._meta.app_label == 'app1':
            return 'db1'
        return None

    def db_for_write(self, model, **hints):
        if model._meta.app_label == 'app1':
            return 'db1'
        return None

    def allow_relation(self, obj1, obj2, **hints):
        if obj1._meta.app_label == 'app1' or obj2._meta.app_label == 'app1':
           return True
        return None

    def allow_migrate(self, db, app_label, model_name=None, **hints):
        # 限定app1的迁移仅在db1执行
        if app_label == 'app1':
            return db == 'db1'
        return None

# 为第二个非默认数据库db2创建对应路由
class App2Router:
    def db_for_read(self, model, **hints):
        if model._meta.app_label == 'app2':
            return 'db2'
        return None

    def db_for_write(self, model, **hints):
        if model._meta.app_label == 'app2':
            return 'db2'
        return None

    def allow_relation(self, obj1, obj2, **hints):
        if obj1._meta.app_label == 'app2' or obj2._meta.app_label == 'app2':
           return True
        return None

    def allow_migrate(self, db, app_label, model_name=None, **hints):
        if app_label == 'app2':
            return db == 'db2'
        return None

接着在settings.py中添加路由配置:

DATABASE_ROUTERS = ['你的项目名.routers.App1Router', '你的项目名.routers.App2Router']

注意allow_migrate方法必须配置准确,否则Django无法识别模型与数据库的对应关系。

2. 生成指定数据库的迁移文件

执行makemigrations时必须明确指定目标数据库和对应的app,否则Django只会检查默认数据库:

# 为app1生成db1的迁移文件
python manage.py makemigrations app1 --database=db1

# 为app2生成db2的迁移文件
python manage.py makemigrations app2 --database=db2

如果是首次为该数据库生成迁移,可加--initial参数强制生成初始迁移:

python manage.py makemigrations app1 --initial --database=db1

3. 应用迁移到非默认数据库

迁移文件生成后,同样需要指定数据库执行迁移操作:

# 将app1的迁移应用到db1
python manage.py migrate app1 --database=db1

# 将app2的迁移应用到db2
python manage.py migrate app2 --database=db2

解决"No changes detected"问题

遇到该提示的常见原因及解决方法:

  • 路由配置错误:检查routers.py中的allow_migrate方法,确认app与数据库的对应关系是否正确;同时验证模型的class Meta里app_label是否与路由配置一致。
  • 已有对应迁移文件:查看对应app的migrations目录,若存在针对目标数据库的迁移文件,直接执行migrate --database=xxx即可,无需重新生成。
  • 模型与数据库结构一致:若模型已和目标数据库表结构匹配,Django会提示无变化,此时可跳过生成步骤直接执行迁移;若是首次迁移,用--initial参数强制生成即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.02 17:20:03