7

Assuming I have a schema with the name "my_schema", how can I create tables with "django syncdb" for that particular schema? Or is there any other alternatives for quickly creating tables from my django models? I think, by default django creates tables for the "public" schema.

Devasia Joseph
  • 388
  • 4
  • 14
  • Are you talking about option **--database=DATABASE**: *Nominates a database to synchronize. Defaults to the "default" database.* – jpic Dec 30 '11 at 15:00
  • No. I am referring to schema. http://www.postgresql.org/docs/9.0/static/ddl-schemas.html .By default django uses the schema named "public" – Devasia Joseph Dec 30 '11 at 16:54
  • 1
    Django does not use 'public' schema by default. Psycopg2 uses 'public' schema by default (yes i've read the code with grep). You can try to set 'OPTIONS': { 'schema': 'yourschema' } in your DATABASE definition (at the same level than 'USER', 'HOST', etc ...). – jpic Dec 30 '11 at 17:04
  • 3
    According to the source code of psycopg 2.4.1, extras.py line 863: you should prefix your database NAME setting with the schema name and a dot. – jpic Dec 30 '11 at 17:12
  • jpic: that code in extras.py is only invoked when registering a typecaster for automatically converting composite types, it has nothing to do with setting a default schema name, so far, I have been unable to find a way to do. – John Aug 28 '12 at 00:11

2 Answers2

6

First, you must have psycopg2>=2.4.3 [1]. If you have then you can add schema to OPTIONS in dictionary-based database configuration, like this:

DATABASES = {
  'default': {
    'ENGINE': 'django.db.backends.postgresql_psycopg2',
    # ...
    'OPTIONS': {
      'options': '-c search_path=my_schema'
    }
  }
}

Tested on postgresql 8.4 and django 1.3

  1. http://initd.org/psycopg/docs/module.html?highlight=connect#psycopg2.connect
  2. http://www.postgresql.org/docs/8.4/static/libpq-connect.html#LIBPQ-CONNECT-OPTIONS
rombarcz
  • 1,604
  • 13
  • 19
0

I have used following info and work for me

'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'dab_name', 'USER': 'username', 'PASSWORD': 'password', 'HOST': 'localhost', 'PORT': '5432', 'OPTIONS': { 'options': '-c search_path=tours' #schema name } }

Tested on postgresql 9 and django 1.10.2

Thanks @romke