Django和postgresql测试模式

Django和postgresql测试模式,django,postgresql,psycopg2,django-testing,Django,Postgresql,Psycopg2,Django Testing,我将PostgreSQL 9.3和Django 1.7.4与psycopg2 2.5.4一起使用 DBA要求我们为应用程序创建一个模式,而不是使用public 我们定义了模式,必须添加 'OPTIONS': { 'options': '-c search_path=custom-schema-name' }, 设置 在测试期间,Django正在使用相应的名称创建测试数据库,但是我们无法设置自定义模式名称 我试图找到一种设置自定义模式名的方法(我已经读过),但找不到一种在测试期间强制创建

我将PostgreSQL 9.3和Django 1.7.4与psycopg2 2.5.4一起使用

DBA要求我们为应用程序创建一个模式,而不是使用public

我们定义了模式,必须添加

'OPTIONS': {
    'options': '-c search_path=custom-schema-name'
},
设置

在测试期间,Django正在使用相应的名称创建测试数据库,但是我们无法设置自定义模式名称

我试图找到一种设置自定义模式名的方法(我已经读过),但找不到一种在测试期间强制创建模式名的方法

我得到的错误是

django.db.utils.ProgrammingError:未选择要在中创建的架构

当我看到创建的数据库时,它默认创建了公共模式

我部分解决了这个问题,并在搜索路径中添加了模式名public

'OPTIONS': {
    'options': '-c search_path=custom-schema-name,public'
},
但是我想用一个自定义的模式名创建测试数据库


有人知道如何设置测试模式名称吗?

我最后编写了一个自定义测试运行程序来解决这个问题(使用django 1.9.x):

myapp/test/runner.py

from types import MethodType
from django.test.runner import DiscoverRunner
from django.db import connections

def prepare_database(self):
    self.connect()
    self.connection.cursor().execute("""
    CREATE SCHEMA foobar_schema AUTHORIZATION your_user;
    GRANT ALL ON SCHEMA foobar_schema TO your_user;
    """)


class PostgresSchemaTestRunner(DiscoverRunner):

    def setup_databases(self, **kwargs):
        for connection_name in connections:
            connection = connections[connection_name]
            connection.prepare_database = MethodType(prepare_database, connection)
        return super().setup_databases(**kwargs)
TEST_RUNNER = 'myapp.test.runner.PostgresSchemaTestRunner'
设置.py

from types import MethodType
from django.test.runner import DiscoverRunner
from django.db import connections

def prepare_database(self):
    self.connect()
    self.connection.cursor().execute("""
    CREATE SCHEMA foobar_schema AUTHORIZATION your_user;
    GRANT ALL ON SCHEMA foobar_schema TO your_user;
    """)


class PostgresSchemaTestRunner(DiscoverRunner):

    def setup_databases(self, **kwargs):
        for connection_name in connections:
            connection = connections[connection_name]
            connection.prepare_database = MethodType(prepare_database, connection)
        return super().setup_databases(**kwargs)
TEST_RUNNER = 'myapp.test.runner.PostgresSchemaTestRunner'

这里也有同样的问题-您找到解决方案了吗?您可能需要共享吗?:)不,我从来没有找到解决办法。我已经辞职了,我完全忘记了这个问题。我发布这篇文章已经一年了,到目前为止,你的答案是唯一的。我还在寻找让django使用非公共模式的解决方案。这里似乎有一个线程:在django中修复,或者我找到了这个可能的解决方案:Thx,这为我节省了大量调试。对于postgres 11.x、django 2.2.x和psycopg 2.8.x,仍然像charm一样工作。如何在截断表时禁用外键约束?在runner中是否可以使用teardown_databases()呢?