constraints.txt 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203
  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. ``CheckConstraint``
  36. ===================
  37. .. class:: CheckConstraint(*, check, name)
  38. Creates a check constraint in the database.
  39. ``check``
  40. ---------
  41. .. attribute:: CheckConstraint.check
  42. A :class:`Q` object or boolean :class:`~django.db.models.Expression` that
  43. specifies the check you want the constraint to enforce.
  44. For example, ``CheckConstraint(check=Q(age__gte=18), name='age_gte_18')``
  45. ensures the age field is never less than 18.
  46. ``name``
  47. --------
  48. .. attribute:: CheckConstraint.name
  49. The name of the constraint. You must always specify a unique name for the
  50. constraint.
  51. ``UniqueConstraint``
  52. ====================
  53. .. class:: UniqueConstraint(*expressions, fields=(), name=None, condition=None, deferrable=None, include=None, opclasses=())
  54. Creates a unique constraint in the database.
  55. ``expressions``
  56. ---------------
  57. .. attribute:: UniqueConstraint.expressions
  58. .. versionadded:: 4.0
  59. Positional argument ``*expressions`` allows creating functional unique
  60. constraints on expressions and database functions.
  61. For example::
  62. UniqueConstraint(Lower('name').desc(), 'category', name='unique_lower_name_category')
  63. creates a unique constraint on the lowercased value of the ``name`` field in
  64. descending order and the ``category`` field in the default ascending order.
  65. Functional unique constraints have the same database restrictions as
  66. :attr:`Index.expressions`.
  67. ``fields``
  68. ----------
  69. .. attribute:: UniqueConstraint.fields
  70. A list of field names that specifies the unique set of columns you want the
  71. constraint to enforce.
  72. For example, ``UniqueConstraint(fields=['room', 'date'],
  73. name='unique_booking')`` ensures each room can only be booked once for each
  74. date.
  75. ``name``
  76. --------
  77. .. attribute:: UniqueConstraint.name
  78. The name of the constraint. You must always specify a unique name for the
  79. constraint.
  80. ``condition``
  81. -------------
  82. .. attribute:: UniqueConstraint.condition
  83. A :class:`Q` object that specifies the condition you want the constraint to
  84. enforce.
  85. For example::
  86. UniqueConstraint(fields=['user'], condition=Q(status='DRAFT'), name='unique_draft_user')
  87. ensures that each user only has one draft.
  88. These conditions have the same database restrictions as
  89. :attr:`Index.condition`.
  90. ``deferrable``
  91. --------------
  92. .. attribute:: UniqueConstraint.deferrable
  93. Set this parameter to create a deferrable unique constraint. Accepted values
  94. are ``Deferrable.DEFERRED`` or ``Deferrable.IMMEDIATE``. For example::
  95. from django.db.models import Deferrable, UniqueConstraint
  96. UniqueConstraint(
  97. name='unique_order',
  98. fields=['order'],
  99. deferrable=Deferrable.DEFERRED,
  100. )
  101. By default constraints are not deferred. A deferred constraint will not be
  102. enforced until the end of the transaction. An immediate constraint will be
  103. enforced immediately after every command.
  104. .. admonition:: MySQL, MariaDB, and SQLite.
  105. Deferrable unique constraints are ignored on MySQL, MariaDB, and SQLite as
  106. neither supports them.
  107. .. warning::
  108. Deferred unique constraints may lead to a `performance penalty
  109. <https://www.postgresql.org/docs/current/sql-createtable.html#id-1.9.3.85.9.4>`_.
  110. ``include``
  111. -----------
  112. .. attribute:: UniqueConstraint.include
  113. A list or tuple of the names of the fields to be included in the covering
  114. unique index as non-key columns. This allows index-only scans to be used for
  115. queries that select only included fields (:attr:`~UniqueConstraint.include`)
  116. and filter only by unique fields (:attr:`~UniqueConstraint.fields`).
  117. For example::
  118. UniqueConstraint(name='unique_booking', fields=['room', 'date'], include=['full_name'])
  119. will allow filtering on ``room`` and ``date``, also selecting ``full_name``,
  120. while fetching data only from the index.
  121. ``include`` is supported only on PostgreSQL.
  122. Non-key columns have the same database restrictions as :attr:`Index.include`.
  123. ``opclasses``
  124. -------------
  125. .. attribute:: UniqueConstraint.opclasses
  126. The names of the `PostgreSQL operator classes
  127. <https://www.postgresql.org/docs/current/indexes-opclass.html>`_ to use for
  128. this unique index. If you require a custom operator class, you must provide one
  129. for each field in the index.
  130. For example::
  131. UniqueConstraint(name='unique_username', fields=['username'], opclasses=['varchar_pattern_ops'])
  132. creates a unique index on ``username`` using ``varchar_pattern_ops``.
  133. ``opclasses`` are ignored for databases besides PostgreSQL.