diff --git a/django/contrib/gis/db/backends/postgis/schema.py b/django/contrib/gis/db/backends/postgis/schema.py index da45d63af3..a4b4910c36 100644 --- a/django/contrib/gis/db/backends/postgis/schema.py +++ b/django/contrib/gis/db/backends/postgis/schema.py @@ -1,11 +1,11 @@ -from django.db.backends.ddl_references import Statement from django.db.backends.postgresql.schema import DatabaseSchemaEditor +from django.db.models.expressions import Col, Func class PostGISSchemaEditor(DatabaseSchemaEditor): geom_index_type = 'GIST' geom_index_ops_nd = 'GIST_GEOMETRY_OPS_ND' - rast_index_wrapper = 'ST_ConvexHull(%s)' + rast_index_template = 'ST_ConvexHull(%(expressions)s)' sql_alter_column_to_3d = "ALTER COLUMN %(column)s TYPE %(type)s USING ST_Force3D(%(column)s)::%(type)s" sql_alter_column_to_2d = "ALTER COLUMN %(column)s TYPE %(type)s USING ST_Force2D(%(column)s)::%(type)s" @@ -23,29 +23,28 @@ class PostGISSchemaEditor(DatabaseSchemaEditor): return super()._create_index_sql(model, fields=fields, **kwargs) field = fields[0] - field_column = self.quote_name(field.column) - + expressions = None + opclasses = None if field.geom_type == 'RASTER': # For raster fields, wrap index creation SQL statement with ST_ConvexHull. # Indexes on raster columns are based on the convex hull of the raster. - field_column = self.rast_index_wrapper % field_column + expressions = Func(Col(None, field), template=self.rast_index_template) + fields = None elif field.dim > 2 and not field.geography: # Use "nd" ops which are fast on multidimensional cases - field_column = "%s %s" % (field_column, self.geom_index_ops_nd) - if kwargs.get('name') is None: - index_name = '%s_%s_id' % (model._meta.db_table, field.column) + opclasses = [self.geom_index_ops_nd] + if not kwargs.get('name'): + name = '%s_%s_id' % (model._meta.db_table, field.column) else: - index_name = kwargs['name'] + name = kwargs['name'] - return Statement( - self.sql_create_index, - name=self.quote_name(index_name), - table=self.quote_name(model._meta.db_table), + return super()._create_index_sql( + model, + fields=fields, + name=name, using=' USING %s' % self.geom_index_type, - columns=field_column, - extra='', - condition='', - include='', + opclasses=opclasses, + expressions=expressions, ) def _alter_column_type_sql(self, table, old_field, new_field, new_type):