[GIS] PostGIS database to be queried by GeoDjango

geodjangopostgisshapefile

I would like to create a PostgreSQL database (postgreslq-9.1 and postgis-2.0.2) storing several shapefiles but I am uncertain on how to implement it.

I have already done this last year but was pretty uncomfortable beacause I had a table per shapefile, every table signed with its SRID (stored inside geometry_columns table – I was using postgis 1.5, so this was still a table and not a view as in postgis-2).

I had to create a new table every time I converted a shapefile: pretty uncomfortable because I had to query them using Django ORM, and create table mapping on the fly is not trivial.

Is that possible to create one single table having an id indicating the original shapefile and the relative SRID per geometry?

Best Answer

After some experiments, I think I've found in django-mutant the solution that fit my needs. With it, you can create a dynamic model in the following way:

from mutant.contrib.geo.models import GeoModel, GeometryFieldDefinition
from mutant.contrib.numeric.models import SmallIntegerFieldDefinition
from mutant.models import BaseDefinition, ModelDefinition

model_def, created = ModelDefinition.objects.get_or_create(
                         app_label='myApp',
                         object_name='myShape',
                         defaults=dict(
                         bases=(BaseDefinition(base=GeoModel),),
                         fields=(GeometryFieldDefinition(name='the_geom', srid=31258),
                         SmallIntegerFieldDefinition(name='cat'),)
                    )
                )

In this way, calling model_def.model_class() would return the same model as if you had declared the following in your models.py:

class myShape(GeoModel):
    cat = models.SmallIntegerField()
    the_geom = models.GeometryField(srid=31258)
    class Meta:
        db_table = u'myApp'

As you run ModelDefinition.objects.get_or_create() method, a table named mutant_myApp_myShape is created into PostgreSQL with a relative row in geometry_colums table. In addition, this model has a proper id entry inside django-mutant table named mutant_modeldefinition.

Further tests need to be made, but this approach seems a good starting point to me.

Related Question