constraints.txt 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251
  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. .. versionchanged:: 4.1
  28. In older versions, constraints were not checked during model validation.
  29. ``BaseConstraint``
  30. ==================
  31. .. class:: BaseConstraint(name, violation_error_message=None)
  32. Base class for all constraints. Subclasses must implement
  33. ``constraint_sql()``, ``create_sql()``, ``remove_sql()`` and
  34. ``validate()`` methods.
  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_message``
  42. ---------------------------
  43. .. versionadded:: 4.1
  44. .. attribute:: BaseConstraint.violation_error_message
  45. The error message used when ``ValidationError`` is raised during
  46. :ref:`model validation <validating-objects>`. Defaults to
  47. ``"Constraint “%(name)s” is violated."``.
  48. ``validate()``
  49. --------------
  50. .. versionadded:: 4.1
  51. .. method:: BaseConstraint.validate(model, instance, exclude=None, using=DEFAULT_DB_ALIAS)
  52. Validates that the constraint, defined on ``model``, is respected on the
  53. ``instance``. This will do a query on the database to ensure that the
  54. constraint is respected. If fields in the ``exclude`` list are needed to
  55. validate the constraint, the constraint is ignored.
  56. Raise a ``ValidationError`` if the constraint is violated.
  57. This method must be implemented by a subclass.
  58. ``CheckConstraint``
  59. ===================
  60. .. class:: CheckConstraint(*, check, name, violation_error_message=None)
  61. Creates a check constraint in the database.
  62. ``check``
  63. ---------
  64. .. attribute:: CheckConstraint.check
  65. A :class:`Q` object or boolean :class:`~django.db.models.Expression` that
  66. specifies the check you want the constraint to enforce.
  67. For example, ``CheckConstraint(check=Q(age__gte=18), name='age_gte_18')``
  68. ensures the age field is never less than 18.
  69. .. versionchanged:: 4.1
  70. The ``violation_error_message`` argument was added.
  71. ``UniqueConstraint``
  72. ====================
  73. .. class:: UniqueConstraint(*expressions, fields=(), name=None, condition=None, deferrable=None, include=None, opclasses=(), violation_error_message=None)
  74. Creates a unique constraint in the database.
  75. ``expressions``
  76. ---------------
  77. .. attribute:: UniqueConstraint.expressions
  78. .. versionadded:: 4.0
  79. Positional argument ``*expressions`` allows creating functional unique
  80. constraints on expressions and database functions.
  81. For example::
  82. UniqueConstraint(Lower('name').desc(), 'category', name='unique_lower_name_category')
  83. creates a unique constraint on the lowercased value of the ``name`` field in
  84. descending order and the ``category`` field in the default ascending order.
  85. Functional unique constraints have the same database restrictions as
  86. :attr:`Index.expressions`.
  87. ``fields``
  88. ----------
  89. .. attribute:: UniqueConstraint.fields
  90. A list of field names that specifies the unique set of columns you want the
  91. constraint to enforce.
  92. For example, ``UniqueConstraint(fields=['room', 'date'],
  93. name='unique_booking')`` ensures each room can only be booked once for each
  94. date.
  95. ``condition``
  96. -------------
  97. .. attribute:: UniqueConstraint.condition
  98. A :class:`Q` object that specifies the condition you want the constraint to
  99. enforce.
  100. For example::
  101. UniqueConstraint(fields=['user'], condition=Q(status='DRAFT'), name='unique_draft_user')
  102. ensures that each user only has one draft.
  103. These conditions have the same database restrictions as
  104. :attr:`Index.condition`.
  105. ``deferrable``
  106. --------------
  107. .. attribute:: UniqueConstraint.deferrable
  108. Set this parameter to create a deferrable unique constraint. Accepted values
  109. are ``Deferrable.DEFERRED`` or ``Deferrable.IMMEDIATE``. For example::
  110. from django.db.models import Deferrable, UniqueConstraint
  111. UniqueConstraint(
  112. name='unique_order',
  113. fields=['order'],
  114. deferrable=Deferrable.DEFERRED,
  115. )
  116. By default constraints are not deferred. A deferred constraint will not be
  117. enforced until the end of the transaction. An immediate constraint will be
  118. enforced immediately after every command.
  119. .. admonition:: MySQL, MariaDB, and SQLite.
  120. Deferrable unique constraints are ignored on MySQL, MariaDB, and SQLite as
  121. neither supports them.
  122. .. warning::
  123. Deferred unique constraints may lead to a `performance penalty
  124. <https://www.postgresql.org/docs/current/sql-createtable.html#id-1.9.3.85.9.4>`_.
  125. ``include``
  126. -----------
  127. .. attribute:: UniqueConstraint.include
  128. A list or tuple of the names of the fields to be included in the covering
  129. unique index as non-key columns. This allows index-only scans to be used for
  130. queries that select only included fields (:attr:`~UniqueConstraint.include`)
  131. and filter only by unique fields (:attr:`~UniqueConstraint.fields`).
  132. For example::
  133. UniqueConstraint(name='unique_booking', fields=['room', 'date'], include=['full_name'])
  134. will allow filtering on ``room`` and ``date``, also selecting ``full_name``,
  135. while fetching data only from the index.
  136. ``include`` is supported only on PostgreSQL.
  137. Non-key columns have the same database restrictions as :attr:`Index.include`.
  138. ``opclasses``
  139. -------------
  140. .. attribute:: UniqueConstraint.opclasses
  141. The names of the `PostgreSQL operator classes
  142. <https://www.postgresql.org/docs/current/indexes-opclass.html>`_ to use for
  143. this unique index. If you require a custom operator class, you must provide one
  144. for each field in the index.
  145. For example::
  146. UniqueConstraint(name='unique_username', fields=['username'], opclasses=['varchar_pattern_ops'])
  147. creates a unique index on ``username`` using ``varchar_pattern_ops``.
  148. ``opclasses`` are ignored for databases besides PostgreSQL.
  149. ``violation_error_message``
  150. ---------------------------
  151. .. versionadded:: 4.1
  152. .. attribute:: UniqueConstraint.violation_error_message
  153. The error message used when ``ValidationError`` is raised during
  154. :ref:`model validation <validating-objects>`. Defaults to
  155. :attr:`.BaseConstraint.violation_error_message`.
  156. This message is *not used* for :class:`UniqueConstraint`\s with
  157. :attr:`~UniqueConstraint.fields` and without a
  158. :attr:`~UniqueConstraint.condition`. Such :class:`~UniqueConstraint`\s show the
  159. same message as constraints defined with
  160. :attr:`.Field.unique` or in
  161. :attr:`Meta.unique_together <django.db.models.Options.constraints>`.