constraints.txt 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205
  1. =====================
  2. Constraints reference
  3. =====================
  4. .. module:: django.db.models.constraints
  5. .. currentmodule:: django.db.models
  6. The classes defined in this module create database constraints. They are added
  7. in the model :attr:`Meta.constraints <django.db.models.Options.constraints>`
  8. option.
  9. .. admonition:: Referencing built-in constraints
  10. Constraints are defined in ``django.db.models.constraints``, but for
  11. convenience they're imported into :mod:`django.db.models`. The standard
  12. convention is to use ``from django.db import models`` and refer to the
  13. constraints as ``models.<Foo>Constraint``.
  14. .. admonition:: Constraints in abstract base classes
  15. You must always specify a unique name for the constraint. As such, you
  16. cannot normally specify a constraint on an abstract base class, since the
  17. :attr:`Meta.constraints <django.db.models.Options.constraints>` option is
  18. inherited by subclasses, with exactly the same values for the attributes
  19. (including ``name``) each time. To work around name collisions, part of the
  20. name may contain ``'%(app_label)s'`` and ``'%(class)s'``, which are
  21. replaced, respectively, by the lowercased app label and class name of the
  22. concrete model. For example ``CheckConstraint(check=Q(age__gte=18),
  23. name='%(app_label)s_%(class)s_is_adult')``.
  24. .. admonition:: Validation of Constraints
  25. In general constraints are **not** checked during ``full_clean()``, and do
  26. not raise ``ValidationError``\s. Rather you'll get a database integrity
  27. error on ``save()``. ``UniqueConstraint``\s without a
  28. :attr:`~UniqueConstraint.condition` (i.e. non-partial unique constraints)
  29. and :attr:`~UniqueConstraint.expressions` (i.e. non-functional unique
  30. constraints) are different in this regard, in that they leverage the
  31. existing ``validate_unique()`` logic, and thus enable two-stage validation.
  32. In addition to ``IntegrityError`` on ``save()``, ``ValidationError`` is
  33. also raised during model validation when the ``UniqueConstraint`` is
  34. violated.
  35. ``BaseConstraint``
  36. ==================
  37. .. class:: BaseConstraint(name)
  38. Base class for all constraints. Subclasses must implement
  39. ``constraint_sql()``, ``create_sql()``, and ``remove_sql()`` methods.
  40. All constraints have the following parameters in common:
  41. ``name``
  42. --------
  43. .. attribute:: BaseConstraint.name
  44. The name of the constraint. You must always specify a unique name for the
  45. constraint.
  46. ``CheckConstraint``
  47. ===================
  48. .. class:: CheckConstraint(*, check, name)
  49. Creates a check constraint in the database.
  50. ``check``
  51. ---------
  52. .. attribute:: CheckConstraint.check
  53. A :class:`Q` object or boolean :class:`~django.db.models.Expression` that
  54. specifies the check you want the constraint to enforce.
  55. For example, ``CheckConstraint(check=Q(age__gte=18), name='age_gte_18')``
  56. ensures the age field is never less than 18.
  57. ``UniqueConstraint``
  58. ====================
  59. .. class:: UniqueConstraint(*expressions, fields=(), name=None, condition=None, deferrable=None, include=None, opclasses=())
  60. Creates a unique constraint in the database.
  61. ``expressions``
  62. ---------------
  63. .. attribute:: UniqueConstraint.expressions
  64. .. versionadded:: 4.0
  65. Positional argument ``*expressions`` allows creating functional unique
  66. constraints on expressions and database functions.
  67. For example::
  68. UniqueConstraint(Lower('name').desc(), 'category', name='unique_lower_name_category')
  69. creates a unique constraint on the lowercased value of the ``name`` field in
  70. descending order and the ``category`` field in the default ascending order.
  71. Functional unique constraints have the same database restrictions as
  72. :attr:`Index.expressions`.
  73. ``fields``
  74. ----------
  75. .. attribute:: UniqueConstraint.fields
  76. A list of field names that specifies the unique set of columns you want the
  77. constraint to enforce.
  78. For example, ``UniqueConstraint(fields=['room', 'date'],
  79. name='unique_booking')`` ensures each room can only be booked once for each
  80. date.
  81. ``condition``
  82. -------------
  83. .. attribute:: UniqueConstraint.condition
  84. A :class:`Q` object that specifies the condition you want the constraint to
  85. enforce.
  86. For example::
  87. UniqueConstraint(fields=['user'], condition=Q(status='DRAFT'), name='unique_draft_user')
  88. ensures that each user only has one draft.
  89. These conditions have the same database restrictions as
  90. :attr:`Index.condition`.
  91. ``deferrable``
  92. --------------
  93. .. attribute:: UniqueConstraint.deferrable
  94. Set this parameter to create a deferrable unique constraint. Accepted values
  95. are ``Deferrable.DEFERRED`` or ``Deferrable.IMMEDIATE``. For example::
  96. from django.db.models import Deferrable, UniqueConstraint
  97. UniqueConstraint(
  98. name='unique_order',
  99. fields=['order'],
  100. deferrable=Deferrable.DEFERRED,
  101. )
  102. By default constraints are not deferred. A deferred constraint will not be
  103. enforced until the end of the transaction. An immediate constraint will be
  104. enforced immediately after every command.
  105. .. admonition:: MySQL, MariaDB, and SQLite.
  106. Deferrable unique constraints are ignored on MySQL, MariaDB, and SQLite as
  107. neither supports them.
  108. .. warning::
  109. Deferred unique constraints may lead to a `performance penalty
  110. <https://www.postgresql.org/docs/current/sql-createtable.html#id-1.9.3.85.9.4>`_.
  111. ``include``
  112. -----------
  113. .. attribute:: UniqueConstraint.include
  114. A list or tuple of the names of the fields to be included in the covering
  115. unique index as non-key columns. This allows index-only scans to be used for
  116. queries that select only included fields (:attr:`~UniqueConstraint.include`)
  117. and filter only by unique fields (:attr:`~UniqueConstraint.fields`).
  118. For example::
  119. UniqueConstraint(name='unique_booking', fields=['room', 'date'], include=['full_name'])
  120. will allow filtering on ``room`` and ``date``, also selecting ``full_name``,
  121. while fetching data only from the index.
  122. ``include`` is supported only on PostgreSQL.
  123. Non-key columns have the same database restrictions as :attr:`Index.include`.
  124. ``opclasses``
  125. -------------
  126. .. attribute:: UniqueConstraint.opclasses
  127. The names of the `PostgreSQL operator classes
  128. <https://www.postgresql.org/docs/current/indexes-opclass.html>`_ to use for
  129. this unique index. If you require a custom operator class, you must provide one
  130. for each field in the index.
  131. For example::
  132. UniqueConstraint(name='unique_username', fields=['username'], opclasses=['varchar_pattern_ops'])
  133. creates a unique index on ``username`` using ``varchar_pattern_ops``.
  134. ``opclasses`` are ignored for databases besides PostgreSQL.