简体   繁体   中英

Django migrate multiple databases

Environment: Django 2, Python 3.6, PostgreSQL (optional)

I am writing an application with multiple models, some of them might be stored in different databases.

Example:

models.py (might be in different apps)

# this used to allow field 'database' to be processed in 'Meta'
models.options.DEFAULT_NAMES = models.options.DEFAULT_NAMES + ('database', )

class MyModel01(models.Model):
    ...
    # this goes to default database


class MyModel02(models.Model):
    ...

    class Meta:
        database = 'mydb02'


class MyModel03(models.Model):
    ...

    class Meta:
        database = 'mydb03'

routers.py:

class MyRouter(object):
    def db_for_read(self, model, **hints):
        return getattr(model._meta, 'database', None)

    def db_for_write(self, model, **hints):
        return getattr(model._meta, 'database', None)

    def allow_migrate(self, db, app_label, model_name=None, **hints):
        model = hints.get('model')
        if not model:
            return None
        if db != 'default':
            modelname = model_name or model._meta.model_name
            usedb = getattr(model._meta, 'database', None)
            if not usedb:
                return False

            if modelname and usedb:
                return usedb == db
            return False
        else:
            usedb = getattr(model._meta, 'database', 'default')
            return usedb == db
        return None

settings:

DATABASES: {
    'default': {
        # some db settings
    },
    'mydb02': {
        # db settings
    },
    'mydb03': {
        # the SAME db settings as for mydb02
    }
}

The issue is that in settings there might be the same database set for all database aliases.

When I run migrate the migration get applied to just one of the databases, but not always to required one. For example it gets applied to 'default', but not 'mydb03'.

I suppose the mistake is in my router, but cannot find out correct implementation.

You can specify which database to use:

python3 manage.py migrate # default database
python3 manage.py migrate --database mydb02
python3 manage.py migrate --database mydb03

https://docs.djangoproject.com/en/2.0/topics/db/multi-db/#synchronizing-your-databases

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM