constraints.txt 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328
  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(condition=Q(age__gte=18),
  23. name='%(app_label)s_%(class)s_is_adult')``.
  24. .. admonition:: Validation of Constraints
  25. Constraints are checked during the :ref:`model validation
  26. <validating-objects>`.
  27. ``BaseConstraint``
  28. ==================
  29. .. class:: BaseConstraint(* name, violation_error_code=None, violation_error_message=None)
  30. Base class for all constraints. Subclasses must implement
  31. ``constraint_sql()``, ``create_sql()``, ``remove_sql()`` and
  32. ``validate()`` methods.
  33. .. deprecated:: 5.0
  34. Support for passing positional arguments is deprecated.
  35. All constraints have the following parameters in common:
  36. ``name``
  37. --------
  38. .. attribute:: BaseConstraint.name
  39. The name of the constraint. You must always specify a unique name for the
  40. constraint.
  41. ``violation_error_code``
  42. ------------------------
  43. .. attribute:: BaseConstraint.violation_error_code
  44. The error code used when ``ValidationError`` is raised during
  45. :ref:`model validation <validating-objects>`. Defaults to ``None``.
  46. ``violation_error_message``
  47. ---------------------------
  48. .. attribute:: BaseConstraint.violation_error_message
  49. The error message used when ``ValidationError`` is raised during
  50. :ref:`model validation <validating-objects>`. Defaults to
  51. ``"Constraint “%(name)s” is violated."``.
  52. ``validate()``
  53. --------------
  54. .. method:: BaseConstraint.validate(model, instance, exclude=None, using=DEFAULT_DB_ALIAS)
  55. Validates that the constraint, defined on ``model``, is respected on the
  56. ``instance``. This will do a query on the database to ensure that the
  57. constraint is respected. If fields in the ``exclude`` list are needed to
  58. validate the constraint, the constraint is ignored.
  59. Raise a ``ValidationError`` if the constraint is violated.
  60. This method must be implemented by a subclass.
  61. ``CheckConstraint``
  62. ===================
  63. .. class:: CheckConstraint(*, condition, name, violation_error_code=None, violation_error_message=None)
  64. Creates a check constraint in the database.
  65. ``condition``
  66. -------------
  67. .. attribute:: CheckConstraint.condition
  68. A :class:`Q` object or boolean :class:`~django.db.models.Expression` that
  69. specifies the conditional check you want the constraint to enforce.
  70. For example, ``CheckConstraint(condition=Q(age__gte=18), name='age_gte_18')``
  71. ensures the age field is never less than 18.
  72. .. admonition:: Expression order
  73. ``Q`` argument order is not necessarily preserved, however the order of
  74. ``Q`` expressions themselves are preserved. This may be important for
  75. databases that preserve check constraint expression order for performance
  76. reasons. For example, use the following format if order matters::
  77. CheckConstraint(
  78. condition=Q(age__gte=18) & Q(expensive_check=condition),
  79. name="age_gte_18_and_others",
  80. )
  81. .. admonition:: Oracle < 23c
  82. Checks with nullable fields on Oracle < 23c must include a condition
  83. allowing for ``NULL`` values in order for :meth:`~BaseConstraint.validate`
  84. to behave the same as check constraints validation. For example, if ``age``
  85. is a nullable field::
  86. CheckConstraint(condition=Q(age__gte=18) | Q(age__isnull=True), name="age_gte_18")
  87. .. deprecated:: 5.1
  88. The ``check`` attribute is deprecated in favor of ``condition``.
  89. ``UniqueConstraint``
  90. ====================
  91. .. class:: UniqueConstraint(*expressions, fields=(), name=None, condition=None, deferrable=None, include=None, opclasses=(), nulls_distinct=None, violation_error_code=None, violation_error_message=None)
  92. Creates a unique constraint in the database.
  93. ``expressions``
  94. ---------------
  95. .. attribute:: UniqueConstraint.expressions
  96. Positional argument ``*expressions`` allows creating functional unique
  97. constraints on expressions and database functions.
  98. For example::
  99. UniqueConstraint(Lower("name").desc(), "category", name="unique_lower_name_category")
  100. creates a unique constraint on the lowercased value of the ``name`` field in
  101. descending order and the ``category`` field in the default ascending order.
  102. Functional unique constraints have the same database restrictions as
  103. :attr:`Index.expressions`.
  104. ``fields``
  105. ----------
  106. .. attribute:: UniqueConstraint.fields
  107. A list of field names that specifies the unique set of columns you want the
  108. constraint to enforce.
  109. For example, ``UniqueConstraint(fields=['room', 'date'],
  110. name='unique_booking')`` ensures each room can only be booked once for each
  111. date.
  112. ``condition``
  113. -------------
  114. .. attribute:: UniqueConstraint.condition
  115. A :class:`Q` object that specifies the condition you want the constraint to
  116. enforce.
  117. For example::
  118. UniqueConstraint(fields=["user"], condition=Q(status="DRAFT"), name="unique_draft_user")
  119. ensures that each user only has one draft.
  120. These conditions have the same database restrictions as
  121. :attr:`Index.condition`.
  122. ``deferrable``
  123. --------------
  124. .. attribute:: UniqueConstraint.deferrable
  125. Set this parameter to create a deferrable unique constraint. Accepted values
  126. are ``Deferrable.DEFERRED`` or ``Deferrable.IMMEDIATE``. For example::
  127. from django.db.models import Deferrable, UniqueConstraint
  128. UniqueConstraint(
  129. name="unique_order",
  130. fields=["order"],
  131. deferrable=Deferrable.DEFERRED,
  132. )
  133. By default constraints are not deferred. A deferred constraint will not be
  134. enforced until the end of the transaction. An immediate constraint will be
  135. enforced immediately after every command.
  136. .. admonition:: MySQL, MariaDB, and SQLite.
  137. Deferrable unique constraints are ignored on MySQL, MariaDB, and SQLite as
  138. neither supports them.
  139. .. warning::
  140. Deferred unique constraints may lead to a `performance penalty
  141. <https://www.postgresql.org/docs/current/sql-createtable.html#id-1.9.3.85.9.4>`_.
  142. ``include``
  143. -----------
  144. .. attribute:: UniqueConstraint.include
  145. A list or tuple of the names of the fields to be included in the covering
  146. unique index as non-key columns. This allows index-only scans to be used for
  147. queries that select only included fields (:attr:`~UniqueConstraint.include`)
  148. and filter only by unique fields (:attr:`~UniqueConstraint.fields`).
  149. For example::
  150. UniqueConstraint(name="unique_booking", fields=["room", "date"], include=["full_name"])
  151. will allow filtering on ``room`` and ``date``, also selecting ``full_name``,
  152. while fetching data only from the index.
  153. Unique constraints with non-key columns are ignored for databases besides
  154. PostgreSQL.
  155. Non-key columns have the same database restrictions as :attr:`Index.include`.
  156. ``opclasses``
  157. -------------
  158. .. attribute:: UniqueConstraint.opclasses
  159. The names of the `PostgreSQL operator classes
  160. <https://www.postgresql.org/docs/current/indexes-opclass.html>`_ to use for
  161. this unique index. If you require a custom operator class, you must provide one
  162. for each field in the index.
  163. For example::
  164. UniqueConstraint(
  165. name="unique_username", fields=["username"], opclasses=["varchar_pattern_ops"]
  166. )
  167. creates a unique index on ``username`` using ``varchar_pattern_ops``.
  168. ``opclasses`` are ignored for databases besides PostgreSQL.
  169. ``nulls_distinct``
  170. ------------------
  171. .. attribute:: UniqueConstraint.nulls_distinct
  172. Whether rows containing ``NULL`` values covered by the unique constraint should
  173. be considered distinct from each other. The default value is ``None`` which
  174. uses the database default which is ``True`` on most backends.
  175. For example::
  176. UniqueConstraint(name="ordering", fields=["ordering"], nulls_distinct=False)
  177. creates a unique constraint that only allows one row to store a ``NULL`` value
  178. in the ``ordering`` column.
  179. Unique constraints with ``nulls_distinct`` are ignored for databases besides
  180. PostgreSQL 15+.
  181. ``violation_error_code``
  182. ------------------------
  183. .. attribute:: UniqueConstraint.violation_error_code
  184. The error code used when a ``ValidationError`` is raised during
  185. :ref:`model validation <validating-objects>`.
  186. Defaults to :attr:`.BaseConstraint.violation_error_code`, when either
  187. :attr:`.UniqueConstraint.condition` is set or :attr:`.UniqueConstraint.fields`
  188. is not set.
  189. If :attr:`.UniqueConstraint.fields` is set without a
  190. :attr:`.UniqueConstraint.condition`, defaults to the :attr:`Meta.unique_together
  191. <django.db.models.Options.unique_together>` error code when there are multiple
  192. fields, and to the :attr:`.Field.unique` error code when there is a single
  193. field.
  194. .. versionchanged:: 5.2
  195. In older versions, the provided
  196. :attr:`.UniqueConstraint.violation_error_code` was not used when
  197. :attr:`.UniqueConstraint.fields` was set without a
  198. :attr:`.UniqueConstraint.condition`.
  199. ``violation_error_message``
  200. ---------------------------
  201. .. attribute:: UniqueConstraint.violation_error_message
  202. The error message used when a ``ValidationError`` is raised during
  203. :ref:`model validation <validating-objects>`.
  204. Defaults to :attr:`.BaseConstraint.violation_error_message`, when either
  205. :attr:`.UniqueConstraint.condition` is set or :attr:`.UniqueConstraint.fields`
  206. is not set.
  207. If :attr:`.UniqueConstraint.fields` is set without a
  208. :attr:`.UniqueConstraint.condition`, defaults to the :attr:`Meta.unique_together
  209. <django.db.models.Options.unique_together>` error message when there are
  210. multiple fields, and to the :attr:`.Field.unique` error message when there is a
  211. single field.
  212. .. versionchanged:: 5.2
  213. In older versions, the provided
  214. :attr:`.UniqueConstraint.violation_error_message` was not used when
  215. :attr:`.UniqueConstraint.fields` was set without a
  216. :attr:`.UniqueConstraint.condition`.