【问题标题】:Django multiple databases error with routesDjango 多数据库路由错误
【发布时间】:2017-06-16 11:33:24
【问题描述】:

我在我的项目中使用了 3 个数据库:

DATABASES = {
    'default': {
        (postgres, read, write)...
    },
    'admission_db': {
        (postgres, read, write)...
    },
    'journals_db': {
        (mysql, read only)...
    }
}
DATABASE_ROUTERS = [
    'main.lib.DbRouter.DbRouter',
]

写了 db 路由器:

class DbRouter:
...

    def allow_migrate(self, db, app_label, model=None, **hints):
        if db == 'admission_db':
            if model and model._meta.app_label == 'admission':
                return True
            return app_label == 'admission'
        elif db == 'journals_db':
            return False
        return None

当我发出迁移命令时

python manage.py migrate admission --database admission_db

它可以正常迁移,但是当我尝试制作时

python manage.py migrate,

它抛出

django.db.utils.OperationalError: no such table: admission_educationform

因此,我可以在其他应用程序上进行 make 迁移。 (蟒蛇3.5.2,django 1.10.5) 什么可能导致问题?

【问题讨论】:

  • $ python manage.py migrate --fake 解决了这个问题,我可以迁移其他应用程序中的更改,但我希望有另一种解决方案,使$ python manage.py migrate 迁移所有没有数据库和应用程序选项的应用程序

标签: django django-migrations


【解决方案1】:

添加了对 magration 中使用的 db 的检查:

def allow_migrate(self, db, app_label, model=None, **hints):
    if db == 'default':
        if app_label == 'admission':
            return False
        elif model and model._meta.app_label == 'admission':
            return False
    if db == 'admission_db':
        if model and model._meta.app_label == 'admission':
            return True
        return app_label == 'admission'
    elif db == 'journals_db':
        return False
    return None

所以,我应该启动 2 个迁移命令:

python migrate admission
python migrate

现在可以正常使用了。

【讨论】:

    猜你喜欢
    • 2011-12-24
    • 1970-01-01
    • 2012-03-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多