title: How to connect to multiple PostgreSQL schemas from Django?
body: <p>In my GeoDjango project I want to connect to a legacy PostgreSQL/PostGIS database. It contains the following schemas:</p>
  
  <ul>
  <li>data // contains all the geospatial data</li>
  <li>django // empty, created by me</li>
  <li>public // system tables such as <code>spatial_ref_sys</code></li>
  </ul>
  
  <p>I want the Django tables shown in the screenshot to go into the <code>django</code> schema. I do not want to pollute the <code>public</code> schema.</p>
  
  <p><a href="https://i.stack.imgur.com/NrLzA.png" rel="noreferrer"><img src="https://i.stack.imgur.com/NrLzA.png" alt="Django tables"></a></p>
  
  <p>I want the "data" models to connect to the <code>data</code> schema. I already tried to <a href="https://docs.djangoproject.com/en/1.8/howto/legacy-databases/" rel="noreferrer">generate models from the legacy tables</a> but <code>python manage.py inspectdb</code> connects to the <code>public</code> schema.</p>
  
  <hr>
  
  <p>In order to provide access to the different schemas I adapted the <a href="http://blog.amvtek.com/posts/2014/Jun/13/accessing-multiple-postgres-schemas-from-django/" rel="noreferrer">approach 2 of this article</a> which preassigns individual <code>search_path</code> values to specific database users:</p>
  
  <pre><code>-- 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;
  </code></pre>
  
  <p>Then I configured the database connections as follows:</p>
  
  <pre><code>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',
      },
  }
  </code></pre>
  
  <p>How can I actually configure that Django uses the <code>django</code> schema while "data" models connect to the <code>data</code> schema?</p>
  
  <hr>
  
  <h3>Readings</h3>
  
  <ul>
  <li><a href="https://stackoverflow.com/questions/1160598/how-to-use-schemas-in-django">How to use schemas in Django?</a></li>
  <li><a href="https://stackoverflow.com/questions/8680673/how-to-specify-schema-name-while-running-syncdb-in-django">How to specify schema name while running &quot;syncdb&quot; in django?</a></li>
  <li><a href="https://code.djangoproject.com/ticket/6148#no2" rel="noreferrer">Issue #6148 - Add generic support for database schemas</a></li>
  </ul>