【问题标题】:Running inspectdb on a specific schema在特定模式上运行 inspectdb
【发布时间】:2014-03-26 01:34:45
【问题描述】:

我想使用inspectdb 为新引入的表格构建相应的模型。但是看起来这个命令只查找public 模式,而新表在另一个表中。

是否可以为inspectdb 指定架构?

【问题讨论】:

    标签: django postgresql


    【解决方案1】:

    是的,您必须指定 search_path,方法是在 settings.py 的 DATABASES 变量中添加一个选项,如下所示:

    'OPTIONS': {
           'options': '-c search_path=myschema'
    }
    

    完整的 DATABASES 变量应该是:

    DATABASES = {
        'default': {
            'ENGINE': 'django.db.backends.postgresql_psycopg2',
            'NAME': 'mydatabase',
            'USER': 'postgres',
            'PASSWORD': 'mypassword',
            'HOST': 'localhost',
            'PORT': '5432',
            'OPTIONS': {
                'options': '-c search_path=myschema'
            }
        }
    }
    

    之后python manage.py inspectdb 应该可以在您的架构上运行

    【讨论】:

    • 指定 'search_path' 不会改变它的行为。它仍然只从 dbo 模式导入。
    【解决方案2】:

    基于this Gist,我修改了django.core.management.commands.inspectdb:在第32行左右,在handle_inspection(),在cursor = connection.cursor()之后,添加cursor.execute("SET search_path TO myotherschema")

    def handle_inspection(self, options):
        connection = connections[options.get('database')]
    
        table2model = lambda table_name: table_name.title().replace('_', '').replace(' ', '').replace('-', '')
    
        cursor = connection.cursor()
        cursor.execute("SET search_path TO myotherschema")
        # [...]
    

    至少从 Django 1.9 开始:

    def handle_inspection(self, options):
        # [...]
        with connection.cursor() as cursor:
            cursor.execute("SET search_path TO myotherschema")
            # [...]
    

    【讨论】:

    【解决方案3】:

    在文件 settings.py 中添加 SCHEMA_TO_INSPECT = 'myschema'inspectdb 将在指定架构中搜索

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-12-03
      • 2023-04-02
      • 1970-01-01
      • 2012-08-01
      • 1970-01-01
      相关资源
      最近更新 更多