settings.py
INSTALLED_APPS = [
...
'app1.apps.App1Config',
'app2.apps.App2Config',
]
DATABASES = {
'default': {
....
},
'db2': {
....
},
}
DATABASE_ROUTERS = ['config.db_router.DbRouter']
modelに追加
※重要
ここのapp_labelをmodel_routerで識別する
class User(models.Model):
class Meta:
app_label = 'apiv2'
ファイル追加
config/db_router.py
class DbRouter:
def db_for_read(self, model, **hints):
if model._meta.app_label == 'apiv1':
return 'default'
if model._meta.app_label == 'apiv2':
return 'db2'
return None
def db_for_write(self, model, **hints):
if model._meta.app_label == 'apiv1':
return 'default'
if model._meta.app_label == 'apiv2':
return 'db2'
return None
def allow_relation(self, obj1, obj2, **hints):
return True
def allow_migrate(self, db, app_label, model=None, **hints):
if app_label == 'auth' or app_label == 'contenttypes' or app_label == 'sessions' or app_label == 'admin':
return db == 'default'
if app_label == 'apiv1':
return db == 'default'
if app_label == 'apiv2':
return db == 'db2'
return None
migrate
CORS_ORIGIN_ALLOW_ALL
CORS_ORIGIN_WHITELIST
が邪魔するので一旦コメントアウト
docker-compose run back ./manage.py makemigrations
docker-compose run back ./manage.py migrate --database=db2