constraints.txt 10 KB

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