indexes.txt 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. =====================
  2. Model index reference
  3. =====================
  4. .. module:: django.db.models.indexes
  5. .. currentmodule:: django.db.models
  6. Index classes ease creating database indexes. They can be added using the
  7. :attr:`Meta.indexes <django.db.models.Options.indexes>` option. This document
  8. explains the API references of :class:`Index` which includes the `index
  9. options`_.
  10. .. admonition:: Referencing built-in indexes
  11. Indexes are defined in ``django.db.models.indexes``, but for convenience
  12. they're imported into :mod:`django.db.models`. The standard convention is
  13. to use ``from django.db import models`` and refer to the indexes as
  14. ``models.<IndexClass>``.
  15. ``Index`` options
  16. =================
  17. .. class:: Index(fields=(), name=None, db_tablespace=None)
  18. Creates an index (B-Tree) in the database.
  19. ``fields``
  20. ----------
  21. .. attribute:: Index.fields
  22. A list or tuple of the name of the fields on which the index is desired.
  23. By default, indexes are created with an ascending order for each column. To
  24. define an index with a descending order for a column, add a hyphen before the
  25. field's name.
  26. For example ``Index(fields=['headline', '-pub_date'])`` would create SQL with
  27. ``(headline, pub_date DESC)``. Index ordering isn't supported on MySQL. In that
  28. case, a descending index is created as a normal index.
  29. .. versionchanged:: 2.1
  30. Older versions don't accept a tuple.
  31. ``name``
  32. --------
  33. .. attribute:: Index.name
  34. The name of the index. If ``name`` isn't provided Django will auto-generate a
  35. name. For compatibility with different databases, index names cannot be longer
  36. than 30 characters and shouldn't start with a number (0-9) or underscore (_).
  37. ``db_tablespace``
  38. -----------------
  39. .. attribute:: Index.db_tablespace
  40. The name of the :doc:`database tablespace </topics/db/tablespaces>` to use for
  41. this index. For single field indexes, if ``db_tablespace`` isn't provided, the
  42. index is created in the ``db_tablespace`` of the field.
  43. If :attr:`.Field.db_tablespace` isn't specified (or if the index uses multiple
  44. fields), the index is created in tablespace specified in the
  45. :attr:`~django.db.models.Options.db_tablespace` option inside the model's
  46. ``class Meta``. If neither of those tablespaces are set, the index is created
  47. in the same tablespace as the table.
  48. .. seealso::
  49. For a list of PostgreSQL-specific indexes, see
  50. :mod:`django.contrib.postgres.indexes`.