Django 有多个数据库,每个数据库都有自己的一组应用程序

Django has multiple databases and each database has its own group of applications

我有一组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

我试过之后migrateapp1。它不是将架构应用于目标数据库。它转到 default 数据库实例

问题:
将我的应用程序分组到特定数据库实例的正确方法是什么?

参考文献:
我试过其中一些,但其中很多已经过时或没有答案

Official docs

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

Django database router

Different database for each django site

Configure Django Database Routers

Django multi-database routing

multiple databases and multiple models in django

我的错。我必须指定 migrate --database=customer 否则 migration 不会 运行 在其他数据库实例上!