[Django]-Django prevent migrations on remote database

3👍

You want the RemoteDBRouter to be authoritative for remote_db database. You don’t want to control its migrations from the local machine neither for auth and remoteapp or other apps. Other databases are not necessarily controlled by RemoteDBRouter. Therefore you start by:

    if db == 'remote_db':
        return False

The question is if you want sometimes to switch auth and remoteapp to local when you are developing write operation or if you expect only read only access and those tables need never to be created locally. Then you can add:

    if app_label == 'auth' or app_label == 'remoteapp':
        return False

Migrations for other databases can be controlled by a default router or other routers:

    return None

It is more complicated with tests to create a test database locally.

DATABASES = {
    'remote_db': {
        ...
        'HOST': 'some.production.host.com',
        'USER': 'some_readonly_user',   # read-only for security
        'TEST': {
            'HOST': 'localhost',
            ...
        }
    }
}

Optionally you can support read-only access to the remote db also by a router rule:

def db_for_write(model, **hints):
    if model._meta.app_label in ('auth', 'remoteapp'):
        return 'myapp_db'  # or maybe the db 'default' where the model doesn't exist

An exception is better than to harm production data if you are writing by mistake. The router can be overridden by many ways, e.g. by using=db parameter or .using(db) method. To be safe, the connection should be by a read only user.

Leave a comment