I have a group of Django applications need to be placed in its own Postgres database instance
Let say I have app1, app2, app3, app4, app5, app6
. And I have multiple database instances for them
DATABASES = {
"default": env.db("DATABASE_URL", default="postgres://postgres:postgres@localhost:5432/th_life"),
"analytic": env.db("ANALYTIC_URL", default="postgres://postgres:postgres@localhost:5432/th_life_analytic"),
"product": env.db("PRODUCT_URL", default="postgres://postgres:postgres@localhost:5432/th_life_product"),
"customer": env.db("CUSTOMER_URL", default="postgres://postgres:postgres@localhost:5432/th_life_customer"),
}
For sake of simplicity I will give an short example default and customer
I need app1, app2, and app3
go to customer
database instance
class DBRouter(object):
def __init__(self):
print(f"Customize router")
super().__init__()
def db_for_read(self, model, **hints):
# customer information
if model._meta.app_label in ['app1', 'app2', 'app3']:
return 'customer'
return None
def db_for_write(self, model, **hints):
if model._meta.app_label in ['app1', 'app2', 'app3']:
return 'customer'
return None
def allow_relation(self, obj1, obj2, **hints):
if obj1._meta.app_label in ['app1', 'app2', 'app3'] or \
obj2._meta.app_label in ['app1', 'app2', 'app3']:
return True
return None
def allow_migrate(self, db, app_label, model_name=None, **hints):
if app_label in ['app1', 'app2', 'app3']:
return db == 'customer'
return None
After I tried migrate
app1
. It is not apply schema to the target database. It goes to default
database instance
Question:
What is the correct way to group my applications to particular database instance?
References:
I had tried some of them and many of them are outdated or no answers
multiple databases and multiple models in django
Django Database router based on user selection
django database routing with transactions
Dynamic database routing in Django
Django migrations router databases
Different database for each django site