1. =====================
    
  2. Constraints reference
    
  3. =====================
    
  4. 
    
  5. .. module:: django.db.models.constraints
    
  6. 
    
  7. .. currentmodule:: django.db.models
    
  8. 
    
  9. The classes defined in this module create database constraints. They are added
    
  10. in the model :attr:`Meta.constraints <django.db.models.Options.constraints>`
    
  11. option.
    
  12. 
    
  13. .. admonition:: Referencing built-in constraints
    
  14. 
    
  15.     Constraints are defined in ``django.db.models.constraints``, but for
    
  16.     convenience they're imported into :mod:`django.db.models`. The standard
    
  17.     convention is to use ``from django.db import models`` and refer to the
    
  18.     constraints as ``models.<Foo>Constraint``.
    
  19. 
    
  20. .. admonition:: Constraints in abstract base classes
    
  21. 
    
  22.     You must always specify a unique name for the constraint. As such, you
    
  23.     cannot normally specify a constraint on an abstract base class, since the
    
  24.     :attr:`Meta.constraints <django.db.models.Options.constraints>` option is
    
  25.     inherited by subclasses, with exactly the same values for the attributes
    
  26.     (including ``name``) each time. To work around name collisions, part of the
    
  27.     name may contain ``'%(app_label)s'`` and ``'%(class)s'``, which are
    
  28.     replaced, respectively, by the lowercased app label and class name of the
    
  29.     concrete model. For example ``CheckConstraint(check=Q(age__gte=18),
    
  30.     name='%(app_label)s_%(class)s_is_adult')``.
    
  31. 
    
  32. .. admonition:: Validation of Constraints
    
  33. 
    
  34.     Constraints are checked during the :ref:`model validation
    
  35.     <validating-objects>`.
    
  36. 
    
  37. .. admonition:: Validation of Constraints with ``JSONField``
    
  38. 
    
  39.     Constraints containing :class:`~django.db.models.JSONField` may not raise
    
  40.     validation errors as key, index, and path transforms have many
    
  41.     database-specific caveats. This :ticket:`may be fully supported later
    
  42.     <34059>`.
    
  43. 
    
  44.     You should always check that there are no log messages, in the
    
  45.     ``django.db.models`` logger, like *"Got a database error calling check() on
    
  46.     …"* to confirm it's validated properly.
    
  47. 
    
  48. .. versionchanged:: 4.1
    
  49. 
    
  50.     In older versions, constraints were not checked during model validation.
    
  51. 
    
  52. ``BaseConstraint``
    
  53. ==================
    
  54. 
    
  55. .. class:: BaseConstraint(name, violation_error_message=None)
    
  56. 
    
  57.     Base class for all constraints. Subclasses must implement
    
  58.     ``constraint_sql()``, ``create_sql()``, ``remove_sql()`` and
    
  59.     ``validate()`` methods.
    
  60. 
    
  61. All constraints have the following parameters in common:
    
  62. 
    
  63. ``name``
    
  64. --------
    
  65. 
    
  66. .. attribute:: BaseConstraint.name
    
  67. 
    
  68. The name of the constraint. You must always specify a unique name for the
    
  69. constraint.
    
  70. 
    
  71. ``violation_error_message``
    
  72. ---------------------------
    
  73. 
    
  74. .. versionadded:: 4.1
    
  75. 
    
  76. .. attribute:: BaseConstraint.violation_error_message
    
  77. 
    
  78. The error message used when ``ValidationError`` is raised during
    
  79. :ref:`model validation <validating-objects>`. Defaults to
    
  80. ``"Constraint ā€œ%(name)sā€ is violated."``.
    
  81. 
    
  82. ``validate()``
    
  83. --------------
    
  84. 
    
  85. .. versionadded:: 4.1
    
  86. 
    
  87. .. method:: BaseConstraint.validate(model, instance, exclude=None, using=DEFAULT_DB_ALIAS)
    
  88. 
    
  89. Validates that the constraint, defined on ``model``, is respected on the
    
  90. ``instance``. This will do a query on the database to ensure that the
    
  91. constraint is respected. If fields in the ``exclude`` list are needed to
    
  92. validate the constraint, the constraint is ignored.
    
  93. 
    
  94. Raise a ``ValidationError`` if the constraint is violated.
    
  95. 
    
  96. This method must be implemented by a subclass.
    
  97. 
    
  98. ``CheckConstraint``
    
  99. ===================
    
  100. 
    
  101. .. class:: CheckConstraint(*, check, name, violation_error_message=None)
    
  102. 
    
  103.     Creates a check constraint in the database.
    
  104. 
    
  105. ``check``
    
  106. ---------
    
  107. 
    
  108. .. attribute:: CheckConstraint.check
    
  109. 
    
  110. A :class:`Q` object or boolean :class:`~django.db.models.Expression` that
    
  111. specifies the check you want the constraint to enforce.
    
  112. 
    
  113. For example, ``CheckConstraint(check=Q(age__gte=18), name='age_gte_18')``
    
  114. ensures the age field is never less than 18.
    
  115. 
    
  116. .. admonition:: Oracle
    
  117. 
    
  118.     Checks with nullable fields on Oracle must include a condition allowing for
    
  119.     ``NULL`` values in order for :meth:`validate() <BaseConstraint.validate>`
    
  120.     to behave the same as check constraints validation. For example, if ``age``
    
  121.     is a nullable field::
    
  122. 
    
  123.         CheckConstraint(check=Q(age__gte=18) | Q(age__isnull=True), name='age_gte_18')
    
  124. 
    
  125. .. versionchanged:: 4.1
    
  126. 
    
  127.     The ``violation_error_message`` argument was added.
    
  128. 
    
  129. ``UniqueConstraint``
    
  130. ====================
    
  131. 
    
  132. .. class:: UniqueConstraint(*expressions, fields=(), name=None, condition=None, deferrable=None, include=None, opclasses=(), violation_error_message=None)
    
  133. 
    
  134.     Creates a unique constraint in the database.
    
  135. 
    
  136. ``expressions``
    
  137. ---------------
    
  138. 
    
  139. .. attribute:: UniqueConstraint.expressions
    
  140. 
    
  141. .. versionadded:: 4.0
    
  142. 
    
  143. Positional argument ``*expressions`` allows creating functional unique
    
  144. constraints on expressions and database functions.
    
  145. 
    
  146. For example::
    
  147. 
    
  148.     UniqueConstraint(Lower('name').desc(), 'category', name='unique_lower_name_category')
    
  149. 
    
  150. creates a unique constraint on the lowercased value of the ``name`` field in
    
  151. descending order and the ``category`` field in the default ascending order.
    
  152. 
    
  153. Functional unique constraints have the same database restrictions as
    
  154. :attr:`Index.expressions`.
    
  155. 
    
  156. ``fields``
    
  157. ----------
    
  158. 
    
  159. .. attribute:: UniqueConstraint.fields
    
  160. 
    
  161. A list of field names that specifies the unique set of columns you want the
    
  162. constraint to enforce.
    
  163. 
    
  164. For example, ``UniqueConstraint(fields=['room', 'date'],
    
  165. name='unique_booking')`` ensures each room can only be booked once for each
    
  166. date.
    
  167. 
    
  168. ``condition``
    
  169. -------------
    
  170. 
    
  171. .. attribute:: UniqueConstraint.condition
    
  172. 
    
  173. A :class:`Q` object that specifies the condition you want the constraint to
    
  174. enforce.
    
  175. 
    
  176. For example::
    
  177. 
    
  178.     UniqueConstraint(fields=['user'], condition=Q(status='DRAFT'), name='unique_draft_user')
    
  179. 
    
  180. ensures that each user only has one draft.
    
  181. 
    
  182. These conditions have the same database restrictions as
    
  183. :attr:`Index.condition`.
    
  184. 
    
  185. ``deferrable``
    
  186. --------------
    
  187. 
    
  188. .. attribute:: UniqueConstraint.deferrable
    
  189. 
    
  190. Set this parameter to create a deferrable unique constraint. Accepted values
    
  191. are ``Deferrable.DEFERRED`` or ``Deferrable.IMMEDIATE``. For example::
    
  192. 
    
  193.     from django.db.models import Deferrable, UniqueConstraint
    
  194. 
    
  195.     UniqueConstraint(
    
  196.         name='unique_order',
    
  197.         fields=['order'],
    
  198.         deferrable=Deferrable.DEFERRED,
    
  199.     )
    
  200. 
    
  201. By default constraints are not deferred. A deferred constraint will not be
    
  202. enforced until the end of the transaction. An immediate constraint will be
    
  203. enforced immediately after every command.
    
  204. 
    
  205. .. admonition:: MySQL, MariaDB, and SQLite.
    
  206. 
    
  207.     Deferrable unique constraints are ignored on MySQL, MariaDB, and SQLite as
    
  208.     neither supports them.
    
  209. 
    
  210. .. warning::
    
  211. 
    
  212.     Deferred unique constraints may lead to a `performance penalty
    
  213.     <https://www.postgresql.org/docs/current/sql-createtable.html#id-1.9.3.85.9.4>`_.
    
  214. 
    
  215. ``include``
    
  216. -----------
    
  217. 
    
  218. .. attribute:: UniqueConstraint.include
    
  219. 
    
  220. A list or tuple of the names of the fields to be included in the covering
    
  221. unique index as non-key columns. This allows index-only scans to be used for
    
  222. queries that select only included fields (:attr:`~UniqueConstraint.include`)
    
  223. and filter only by unique fields (:attr:`~UniqueConstraint.fields`).
    
  224. 
    
  225. For example::
    
  226. 
    
  227.     UniqueConstraint(name='unique_booking', fields=['room', 'date'], include=['full_name'])
    
  228. 
    
  229. will allow filtering on ``room`` and ``date``, also selecting ``full_name``,
    
  230. while fetching data only from the index.
    
  231. 
    
  232. ``include`` is supported only on PostgreSQL.
    
  233. 
    
  234. Non-key columns have the same database restrictions as :attr:`Index.include`.
    
  235. 
    
  236. 
    
  237. ``opclasses``
    
  238. -------------
    
  239. 
    
  240. .. attribute:: UniqueConstraint.opclasses
    
  241. 
    
  242. The names of the `PostgreSQL operator classes
    
  243. <https://www.postgresql.org/docs/current/indexes-opclass.html>`_ to use for
    
  244. this unique index. If you require a custom operator class, you must provide one
    
  245. for each field in the index.
    
  246. 
    
  247. For example::
    
  248. 
    
  249.     UniqueConstraint(name='unique_username', fields=['username'], opclasses=['varchar_pattern_ops'])
    
  250. 
    
  251. creates a unique index on ``username`` using ``varchar_pattern_ops``.
    
  252. 
    
  253. ``opclasses`` are ignored for databases besides PostgreSQL.
    
  254. 
    
  255. ``violation_error_message``
    
  256. ---------------------------
    
  257. 
    
  258. .. versionadded:: 4.1
    
  259. 
    
  260. .. attribute:: UniqueConstraint.violation_error_message
    
  261. 
    
  262. The error message used when ``ValidationError`` is raised during
    
  263. :ref:`model validation <validating-objects>`. Defaults to
    
  264. :attr:`.BaseConstraint.violation_error_message`.
    
  265. 
    
  266. This message is *not used* for :class:`UniqueConstraint`\s with
    
  267. :attr:`~UniqueConstraint.fields` and without a
    
  268. :attr:`~UniqueConstraint.condition`. Such :class:`~UniqueConstraint`\s show the
    
  269. same message as constraints defined with
    
  270. :attr:`.Field.unique` or in
    
  271. :attr:`Meta.unique_together <django.db.models.Options.constraints>`.