django - 如何从 Django 连接到多个 PostgreSQL 模式?

标签 django postgresql database-schema postgis geodjango

在我的 GeoDjango 项目中,我想连接到旧版 PostgreSQL/PostGIS 数据库。它包含以下模式:

  • data//包含所有地理空间数据
  • django//空的,由我创建
  • public//系统表如spatial_ref_sys

我希望屏幕截图中显示的 Django 表进入 django 模式。我不想污染 public 架构。

Django tables

我希望“数据”模型连接到 data 模式。我已经尝试过 generate models from the legacy tables但是 python manage.py inspectdb 连接到 public 模式。


为了提供对不同模式的访问,我调整了 approach 2 of this article它将单独的 search_path 值预分配给特定的数据库用户:

-- user accessing django schema...
CREATE ROLE django_user LOGIN PASSWORD 'secret';
ALTER ROLE django_user SET search_path TO django, public;

-- user accessing data schema...
CREATE ROLE data_user LOGIN PASSWORD 'secret';
ALTER ROLE data_user SET search_path TO data, public;

然后我配置数据库连接如下:

DATABASES = {

    'default': {
            'ENGINE': 'django.db.backends.postgresql_psycopg2',
            'NAME': 'multi_schema_db',
            'USER': 'django_user',
            'PASSWORD': 'secret',
    },

    'data': {
            'ENGINE': 'django.db.backends.postgresql_psycopg2',
            'NAME': 'multi_schema_db',
            'USER': 'data_user',
            'PASSWORD': 'secret',
    },
}

当“数据”模型连接到 data 模式时,我如何实际配置 Django 使用 django 模式?


读物

最佳答案

您必须利用 search_path:

DATABASES = {

    'default': {
            'ENGINE': 'django.db.backends.postgresql_psycopg2',
            'OPTIONS' : {
                'options': '-c search_path=django,public'
            },
            'NAME': 'multi_schema_db',
            'USER': 'django_user',
            'PASSWORD': 'secret',
    },

    'data': {
            'ENGINE': 'django.db.backends.postgresql_psycopg2',
            'OPTIONS' : {
                'options': '-c search_path=data,public'
            },
            'NAME': 'multi_schema_db',
            'USER': 'data_user',
            'PASSWORD': 'secret',
    },
}

关于django - 如何从 Django 连接到多个 PostgreSQL 模式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31726064/

相关文章:

java - Hibernate、Postgre/MySQL 差异

java - 在运行时更改 WebSphere 数据源架构

mysql - Web 聊天应用程序数据库架构

mysql - 分层数据 - 嵌套集模型 : MySql

python - Django:追踪 DjangoUnicodeDecodeError 错误

python - Django 唯一的、空的和空白的 CharField 在管理页面上给出 'already exists' 错误

django - 我有一个 TemplateDoesNotExist 错误。我可以更新我的模型但不能删除它们?

python - Django 说字段不存在时它确实存在

php - 如何使数组的输出不同?

postgresql - postgres 9.6 索引仅在逻辑上可能但不执行的功能索引上扫描