2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

django アプリケーション毎に データベースを分ける

Posted at

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  
2
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?