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

时间:2019-07-24 06:44:56

标签: python django database postgresql routing

我有一组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数据库实例

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

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

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

1 个答案:

答案 0 :(得分:0)

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