【问题标题】:Django has multiple databases and each database has its own group of applicationsDjango 有多个数据库,每个数据库都有自己的应用程序组
【发布时间】: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 app3customer 数据库实例

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

【问题讨论】:

    标签: python django database postgresql routing


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 2013-01-09
      • 1970-01-01
      • 1970-01-01
      • 2021-03-04
      • 2014-05-23
      • 2017-03-04
      • 2019-12-16
      • 2015-12-14
      • 2020-03-22
      相关资源
      最近更新 更多