Home>

I want to change the database to connect for each application. . .
((Db1 when app name is app1, db2 when app2 is other) db1 otherwise)

When it is app1, you can connect without problems.
app2 can not be connected. . .

[setting.py]

DATABASES = {
    'db1': {
        'ENGINE': '***',
        'NAME': '***',
        'USER': '***',
        'PASSWORD': '***',
        'HOST': '***',
        'PORT': '***',
    },
    'db2': {
        'ENGINE': 'sql_server.pyodbc',
        'NAME': 'test',
        'USER': 'user',
        'PASSWORD': '******',
        'HOST': '127.0.0.1',
        'PORT': '****',
        'OPTIONS': {
            'driver': 'ODBC Driver 13 for SQL Server',
        },
    }
}

[dbrouter.py]

class Router (object):
    def db_for_read (self, model, ** hints):
        if model._meta.app_label == "app1":
            return None
        if model._meta.app_label == "app2":
            return "db2"
        return "db1"
    def db_for_write (self, model, ** hints):
        if model._meta.app_label == "app1":
            return None
        if model._meta.app_label == "app2":
            return "db2"
        return "db1"
    def allow_relation (self, obj1, obj2, ** hints):
        if obj1._meta.app_label == "app1" and obj2._meta.app_label == "app1":
            return None
        if obj1._meta.app_label == "app2" and obj2._meta.app_label == "app2":
            return "db2"
        return "db1"
    def allow_migrate (self, db, app_label, model = None, ** hints):
        if app_label == "app1":
            return db == "db1"
        if app_label == "app2":
            return db == "db2"
        else:
            return db == "db1"
Error message

manage.py inspectdb --database [DB name]
Since model definitions are listed, I think setting.py is not wrong. .
Then, is dbrouter.py deficient? . .

Notes

It may be difficult to get answers to these configuration questions.
Please let me know if there are any obvious mistakes. . .

  • Answer # 1

    As dameo commented,
    >DATABASE_ROUTERS setting in settings.py
    Because it was missing, it seems that he was going to see the default. . .