Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Running inspectdb on a specific schema

I'd like to use inspectdb in order to build corresponding models for freshly introduced tables. But is looks like this command only looks up the public schema, while the new tables are in another one.

Is it possible to specify a schema to inspectdb ?

like image 344
Anto Avatar asked Feb 24 '14 11:02

Anto


2 Answers

Yes, you have to specify the search_path, by adding an option in your DATABASES variable at settings.py, like that:

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

The full DATABASES variable should be:

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

After that python manage.py inspectdb should work on your schema

like image 150
ugosan Avatar answered Sep 23 '22 17:09

ugosan


Based on this Gist, I modified django.core.management.commands.inspectdb: around line 32, in handle_inspection(), after cursor = connection.cursor(), add 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")
    # [...]

As of, at least, Django 1.9:

def handle_inspection(self, options):
    # [...]
    with connection.cursor() as cursor:
        cursor.execute("SET search_path TO myotherschema")
        # [...]
like image 40
Anto Avatar answered Sep 22 '22 17:09

Anto