【发布时间】:2019-12-02 05:53:21
【问题描述】:
我有一组 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
【问题讨论】:
标签: python django database postgresql routing