Model index reference

New in Django 1.11.

Index classes ease creating database indexes. They can be added using theMeta.indexes option. This documentexplains the API references of Index which includes the indexoptions.

Referencing built-in indexes

Indexes are defined in django.db.models.indexes, but for conveniencethey're imported into django.db.models. The standard convention isto use from django.db import models and refer to the indexes asmodels.<IndexClass>.

Index options

  • class Index(fields=[], name=None, db_tablespace=None)[source]
  • Creates an index (B-Tree) in the database.

fields

  • Index.fields
  • A list of the name of the fields on which the index is desired.

By default, indexes are created with an ascending order for each column. Todefine an index with a descending order for a column, add a hyphen before thefield's name.

For example Index(fields=['headline', '-pub_date']) would create SQL with(headline, pub_date DESC). Index ordering isn't supported on MySQL. In thatcase, a descending index is created as a normal index.

Support for column ordering on SQLite

Column ordering is supported on SQLite 3.3.0+ and only for some databasefile formats. Refer to the SQLite docs for specifics.

name

  • Index.name
  • The name of the index. If name isn't provided Django will auto-generate aname. For compatibility with different databases, index names cannot be longerthan 30 characters and shouldn't start with a number (0-9) or underscore (_).

db_tablespace

  • Index.db_tablespace
  • New in Django 2.0.

The name of the database tablespace to use forthis index. For single field indexes, if db_tablespace isn't provided, theindex is created in the db_tablespace of the field.

If Field.db_tablespace isn't specified (or if the index uses multiplefields), the index is created in tablespace specified in thedb_tablespace option inside the model'sclass Meta. If neither of those tablespaces are set, the index is createdin the same tablespace as the table.

See also

For a list of PostgreSQL-specific indexes, seedjango.contrib.postgres.indexes.