Tablespaces

A common paradigm for optimizing performance in database systems is the use oftablespaces to organize disk layout.

Warning

Django does not create the tablespaces for you. Please refer to yourdatabase engine’s documentation for details on creating and managingtablespaces.

Declaring tablespaces for tables

A tablespace can be specified for the table generated by a model by supplyingthe db_tablespace option inside the model’sclass Meta. This option also affects tables automatically created forManyToManyFields in the model.

You can use the DEFAULT_TABLESPACE setting to specify a default valuefor db_tablespace. This is useful for settinga tablespace for the built-in Django apps and other applications whose code youcannot control.

Declaring tablespaces for indexes

You can pass the db_tablespace option to anIndex constructor to specify the name of a tablespace to use for the index.For single field indexes, you can pass thedb_tablespace option to a Field constructorto specify an alternate tablespace for the field’s column index. If the columndoesn’t have an index, the option is ignored.

You can use the DEFAULT_INDEX_TABLESPACE setting to specifya default value for db_tablespace.

If db_tablespace isn’t specified and you didn’tset DEFAULT_INDEX_TABLESPACE, the index is created in the sametablespace as the tables.

An example

  1. class TablespaceExample(models.Model):
  2. name = models.CharField(max_length=30, db_index=True, db_tablespace="indexes")
  3. data = models.CharField(max_length=255, db_index=True)
  4. shortcut = models.CharField(max_length=7)
  5. edges = models.ManyToManyField(to="self", db_tablespace="indexes")
  6.  
  7. class Meta:
  8. db_tablespace = "tables"
  9. indexes = [models.Index(fields=['shortcut'], db_tablespace='other_indexes')]

In this example, the tables generated by the TablespaceExample model (i.e.the model table and the many-to-many table) would be stored in the tablestablespace. The index for the name field and the indexes on the many-to-manytable would be stored in the indexes tablespace. The data field wouldalso generate an index, but no tablespace for it is specified, so it would bestored in the model tablespace tables by default. The index for theshortcut field would be stored in the other_indexes tablespace.

Database support

PostgreSQL and Oracle support tablespaces. SQLite, MariaDB and MySQL don’t.

When you use a backend that lacks support for tablespaces, Django ignores alltablespace-related options.