How to create tables in different schemas using Geodjango and Postgres/ PostGIS?

62 Views Asked by At

My question is very similar to the question asked and answered here, using the Meta class and db_table = 'schema"."tablename' approach to use multiple schemas: How to create tables in a different schema in django?

This solution worked for me under the standard Django project framework (using django.db models); however, once I attempted to use this method in a Geodjango project (using django.contrib.gis.db models), I received the following error when trying to migrate a model that included geospatial fields (PointField, LineStringField, and PolygonField):

django.db.utils.ProgrammingError: syntax error at or near "."
LINE 1: CREATE INDEX "schema"."tablename_geom_point_id" ON "sch...

How can I implement this approach using Geodjango to leverage the benefits of schemas directly in the model?

Example code of what I tried and resulted in the error message has been presented below.

models.py

import uuid
from django.contrib.gis.db import models


class TableName(models.Model):
    id = models.UUIDField(primary_key = True, default = uuid.uuid4, editable = False)
    ...
    geom_point = models.PointField(blank=True, null=True)
    geom_line = models.LineStringField(blank=True, null=True)
    geom_polygon = models.PolygonField(blank=True, null=True)    
    ...
    
    class Meta:
        managed = True
        db_table = 'schema"."tablename'

Thank you for any support you can provide!

1

There are 1 best solutions below

1
Abdul Aziz On

There's a problem with the way schema and table names are specified when using geodjango, while working with geospatial fields, the naming conventions and behavior can/may be different from regular Django models.

You can perhaps enclose them in '' rather than the "" just for the . - which is the conventional way for sql tables. This is most likely the issue.

from django.contrib.gis.db import models

class TableName(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    # ...
    geom_point = models.PointField(blank=True, null=True)
    geom_line = models.LineStringField(blank=True, null=True)
    geom_polygon = models.PolygonField(blank=True, null=True)
    # ...

    class Meta:
        managed = True
        db_table = 'schema.tablename'