I
I
Ilya Chichak2017-02-01 06:15:17
Django
Ilya Chichak, 2017-02-01 06:15:17

How to set up 2 DBs in Django?

The project uses 3 databases and a database router:

DATABASES = {
    'default': {
        (postgres, читать, писать)...
    },
    'admission_db': {
        (postgres, читать, писать)...
    },
    'journals_db': {
        (mysql, только читать)...
    }
}
DATABASE_ROUTERS = [
    'main.lib.DbRouter.DbRouter',
]

the router itself:
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

when migrating with application and database specified
$ python manage.py migrate admission --database admission_db

migrates fine, but if migrate through
$ python manage.py migrate
an error occurs
django.db.utils.OperationalError: no such table: admission_educationform

how to overcome the problem?
(django 1.10.5, python 3.5.2)
UPD:
by changing allow_migrate():
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

earned. I have to run 2 migrations:
$ python manage.py migrate admission
$ python manage.py migrate

But the error doesn't appear anymore.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
sim3x, 2017-02-01
@ilya_chch

The migrate management command operates on one database at a time. By default, it operates on the default
If, as in the second example above, you've left the default database empty, you must provide a database name each time you run migrate
you can write an alias for all databases or write your own command wrapper

I
Ilya Chichak, 2017-02-01
@ilya_chch

managed to get around the error with
now Django thinks that the migrations are done and there is no error, but I would like to try to find a solution so that you can just run migrate and not take a steam bath

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question