diff --git a/django/db/backends/base/schema.py b/django/db/backends/base/schema.py index 8d019a7983..24e8bc5413 100644 --- a/django/db/backends/base/schema.py +++ b/django/db/backends/base/schema.py @@ -31,7 +31,6 @@ class BaseDatabaseSchemaEditor(object): # Overrideable SQL templates sql_create_table = "CREATE TABLE %(table)s (%(definition)s)" - sql_create_table_unique = "UNIQUE (%(columns)s)" sql_rename_table = "ALTER TABLE %(old_table)s RENAME TO %(new_table)s" sql_retablespace_table = "ALTER TABLE %(table)s SET TABLESPACE %(new_tablespace)s" sql_delete_table = "DROP TABLE %(table)s CASCADE" @@ -263,12 +262,11 @@ class BaseDatabaseSchemaEditor(object): if autoinc_sql: self.deferred_sql.extend(autoinc_sql) - # Add any unique_togethers + # Add any unique_togethers (always deferred, as some fields might be + # created afterwards, like geometry fields with some backends) for fields in model._meta.unique_together: columns = [model._meta.get_field(field).column for field in fields] - column_sqls.append(self.sql_create_table_unique % { - "columns": ", ".join(self.quote_name(column) for column in columns), - }) + self.deferred_sql.append(self._create_unique_sql(model, columns)) # Make the table sql = self.sql_create_table % { "table": self.quote_name(model._meta.db_table), diff --git a/django/db/backends/sqlite3/schema.py b/django/db/backends/sqlite3/schema.py index 70b4458424..26c4771f8f 100644 --- a/django/db/backends/sqlite3/schema.py +++ b/django/db/backends/sqlite3/schema.py @@ -13,6 +13,8 @@ class DatabaseSchemaEditor(BaseDatabaseSchemaEditor): sql_delete_table = "DROP TABLE %(table)s" sql_create_inline_fk = "REFERENCES %(to_table)s (%(to_column)s)" + sql_create_unique = "CREATE UNIQUE INDEX %(name)s ON %(table)s (%(columns)s)" + sql_delete_unique = "DROP INDEX %(name)s" def __enter__(self): with self.connection.cursor() as c: diff --git a/tests/gis_tests/geoapp/models.py b/tests/gis_tests/geoapp/models.py index a0e910684d..877eb7d72c 100644 --- a/tests/gis_tests/geoapp/models.py +++ b/tests/gis_tests/geoapp/models.py @@ -57,6 +57,9 @@ class MultiFields(NamedModel): point = models.PointField() poly = models.PolygonField() + class Meta: + unique_together = ('city', 'point') + class Truth(models.Model): val = models.BooleanField(default=False)