PostgreSql schema support, PostGIS and Django

Posted on Mon 30 July 2012 in django

postgis

&

django

I recently searched for postgresql schema support in django. There is a long standing ticket (opened about 4 years) -- it wants to implement generic support for database schemas.

It is surely all nice and dandy, but I needed an "instant" solution. After a bit of research I have found a nice layer (though the author says WORKSFORME :) ) called django schemata

My personal need was to have also postgis support, so... here we go!:

To add postgres schema support you have to:

  • Set your django ENGINE to django_schemata.postgresql_backend

     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    DATABASES = {
        'default': {
            'ENGINE': 'django_schemata.postgresql_backend',
            'NAME': 'yourdb',
            'USER': 'postgres',
            'PASSWORD': '',
            'HOST': '',
            'PORT': '',
        }
    }
    
  • Add to the top of MIDDLEWARE_CLASSES:

    1
    2
    3
    4
    MIDDLEWARE_CLASSES = (
        'django_schemata.middleware.SchemataMiddleware',
        [...],
    )
    
  • Configure the SCHEMATA_DOMAINS dict

My needs were to have django in the public schema and all the other stuff related to my host inside a particular schema:

1
2
3
4
5
6
7
8
9
SCHEMATA_DOMAINS = {
    'localhost': { # localhost is for development, you should put the
                   #  hostname/ip instead in production mode
        'schema_name': 'mypersonalschema',
    },
    'django': {
        'schema_name': 'public',
    },
}
  • Django Schemata works with south, so we have to add the two to INSTALLED_APPS:
    1
    2
    3
    4
    5
    6
    7
    8
    INSTALLED_APPS = (
        'django.contrib.gis',
        # Uncomment the next line to enable the admin:
        'django.contrib.admin',
        'geonode.observations',
        'south',
        'django_schemata',
    )
    

NOTE: I also added django.contrib.gis because I need postgis support in Django

I had to specify manually the POSTGIS_VERSION variable which is:

1
POSTGIS_VERSION = '1.5.3'

And finally:

1
2
3
4
5
SOUTH_DATABASE_ADAPTERS = {
    'default': 'south.db.postgresql_psycopg2',
}

ORIGINAL_BACKEND = 'django.contrib.gis.db.backends.postgis'

After your settings.py are in place, you can play with django schemata in this way:

1
2
3
4
5
6
7
$ python ./manage.py manage_schemata # creates the schema
$ export DJANGO_SCHEMATA_DOMAIN="django"
$ python ./manage.py syncdb # to create django stuff in the 'public' schema
$ python ./manage.py sync_schemata --migrate # to create/migrate your
                                             # database inside 
                                             # the 'mypersonalschema'
                                             # schema.

Ok, That's all folks for now!