我有一组Django应用程序需要放置在其自己的Postgres数据库实例中
假设我有app1, app2, app3, app4, app5, app6
。我有多个数据库实例
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"),
}
为简单起见,我将举一个简短的示例default and customer
我需要app1, app2, and app3
转到customer
数据库实例
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
尝试migrate
app1
之后。它不是将架构应用于目标数据库。它进入default
数据库实例
问题:
将我的应用程序分组到特定数据库实例的正确方法是什么?
参考文献:
我尝试了其中的一些,但其中许多已经过时或没有答案
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
答案 0 :(得分:0)
我的坏。我必须指定migrate --database=customer
,否则migration
将不会在其他数据库实例上运行!