constraints.txt 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240
  1. ========================================
  2. PostgreSQL specific database constraints
  3. ========================================
  4. .. module:: django.contrib.postgres.constraints
  5. :synopsis: PostgreSQL specific database constraint
  6. PostgreSQL supports additional data integrity constraints available from the
  7. ``django.contrib.postgres.constraints`` module. They are added in the model
  8. :attr:`Meta.constraints <django.db.models.Options.constraints>` option.
  9. ``ExclusionConstraint``
  10. =======================
  11. .. class:: ExclusionConstraint(*, name, expressions, index_type=None, condition=None, deferrable=None, include=None, opclasses=())
  12. Creates an exclusion constraint in the database. Internally, PostgreSQL
  13. implements exclusion constraints using indexes. The default index type is
  14. `GiST <https://www.postgresql.org/docs/current/gist.html>`_. To use them,
  15. you need to activate the `btree_gist extension
  16. <https://www.postgresql.org/docs/current/btree-gist.html>`_ on PostgreSQL.
  17. You can install it using the
  18. :class:`~django.contrib.postgres.operations.BtreeGistExtension` migration
  19. operation.
  20. If you attempt to insert a new row that conflicts with an existing row, an
  21. :exc:`~django.db.IntegrityError` is raised. Similarly, when update
  22. conflicts with an existing row.
  23. ``name``
  24. --------
  25. .. attribute:: ExclusionConstraint.name
  26. The name of the constraint.
  27. ``expressions``
  28. ---------------
  29. .. attribute:: ExclusionConstraint.expressions
  30. An iterable of 2-tuples. The first element is an expression or string. The
  31. second element is an SQL operator represented as a string. To avoid typos, you
  32. may use :class:`~django.contrib.postgres.fields.RangeOperators` which maps the
  33. operators with strings. For example::
  34. expressions=[
  35. ('timespan', RangeOperators.ADJACENT_TO),
  36. (F('room'), RangeOperators.EQUAL),
  37. ]
  38. .. admonition:: Restrictions on operators.
  39. Only commutative operators can be used in exclusion constraints.
  40. The :class:`OpClass() <django.contrib.postgres.indexes.OpClass>` expression can
  41. be used to specify a custom `operator class`_ for the constraint expressions.
  42. For example::
  43. expressions=[
  44. (OpClass('circle', name='circle_ops'), RangeOperators.OVERLAPS),
  45. ]
  46. creates an exclusion constraint on ``circle`` using ``circle_ops``.
  47. .. versionchanged:: 4.1
  48. Support for the ``OpClass()`` expression was added.
  49. .. _operator class: https://www.postgresql.org/docs/current/indexes-opclass.html
  50. ``index_type``
  51. --------------
  52. .. attribute:: ExclusionConstraint.index_type
  53. The index type of the constraint. Accepted values are ``GIST`` or ``SPGIST``.
  54. Matching is case insensitive. If not provided, the default index type is
  55. ``GIST``.
  56. ``condition``
  57. -------------
  58. .. attribute:: ExclusionConstraint.condition
  59. A :class:`~django.db.models.Q` object that specifies the condition to restrict
  60. a constraint to a subset of rows. For example,
  61. ``condition=Q(cancelled=False)``.
  62. These conditions have the same database restrictions as
  63. :attr:`django.db.models.Index.condition`.
  64. ``deferrable``
  65. --------------
  66. .. attribute:: ExclusionConstraint.deferrable
  67. Set this parameter to create a deferrable exclusion constraint. Accepted values
  68. are ``Deferrable.DEFERRED`` or ``Deferrable.IMMEDIATE``. For example::
  69. from django.contrib.postgres.constraints import ExclusionConstraint
  70. from django.contrib.postgres.fields import RangeOperators
  71. from django.db.models import Deferrable
  72. ExclusionConstraint(
  73. name='exclude_overlapping_deferred',
  74. expressions=[
  75. ('timespan', RangeOperators.OVERLAPS),
  76. ],
  77. deferrable=Deferrable.DEFERRED,
  78. )
  79. By default constraints are not deferred. A deferred constraint will not be
  80. enforced until the end of the transaction. An immediate constraint will be
  81. enforced immediately after every command.
  82. .. warning::
  83. Deferred exclusion constraints may lead to a `performance penalty
  84. <https://www.postgresql.org/docs/current/sql-createtable.html#id-1.9.3.85.9.4>`_.
  85. ``include``
  86. -----------
  87. .. attribute:: ExclusionConstraint.include
  88. A list or tuple of the names of the fields to be included in the covering
  89. exclusion constraint as non-key columns. This allows index-only scans to be
  90. used for queries that select only included fields
  91. (:attr:`~ExclusionConstraint.include`) and filter only by indexed fields
  92. (:attr:`~ExclusionConstraint.expressions`).
  93. ``include`` is supported for GiST indexes on PostgreSQL 12+ and SP-GiST
  94. indexes on PostgreSQL 14+.
  95. .. versionchanged:: 4.1
  96. Support for covering exclusion constraints using SP-GiST indexes on
  97. PostgreSQL 14+ was added.
  98. ``opclasses``
  99. -------------
  100. .. attribute:: ExclusionConstraint.opclasses
  101. The names of the `PostgreSQL operator classes
  102. <https://www.postgresql.org/docs/current/indexes-opclass.html>`_ to use for
  103. this constraint. If you require a custom operator class, you must provide one
  104. for each expression in the constraint.
  105. For example::
  106. ExclusionConstraint(
  107. name='exclude_overlapping_opclasses',
  108. expressions=[('circle', RangeOperators.OVERLAPS)],
  109. opclasses=['circle_ops'],
  110. )
  111. creates an exclusion constraint on ``circle`` using ``circle_ops``.
  112. .. deprecated:: 4.1
  113. The ``opclasses`` parameter is deprecated in favor of using
  114. :class:`OpClass() <django.contrib.postgres.indexes.OpClass>` in
  115. :attr:`~ExclusionConstraint.expressions`.
  116. Examples
  117. --------
  118. The following example restricts overlapping reservations in the same room, not
  119. taking canceled reservations into account::
  120. from django.contrib.postgres.constraints import ExclusionConstraint
  121. from django.contrib.postgres.fields import DateTimeRangeField, RangeOperators
  122. from django.db import models
  123. from django.db.models import Q
  124. class Room(models.Model):
  125. number = models.IntegerField()
  126. class Reservation(models.Model):
  127. room = models.ForeignKey('Room', on_delete=models.CASCADE)
  128. timespan = DateTimeRangeField()
  129. cancelled = models.BooleanField(default=False)
  130. class Meta:
  131. constraints = [
  132. ExclusionConstraint(
  133. name='exclude_overlapping_reservations',
  134. expressions=[
  135. ('timespan', RangeOperators.OVERLAPS),
  136. ('room', RangeOperators.EQUAL),
  137. ],
  138. condition=Q(cancelled=False),
  139. ),
  140. ]
  141. In case your model defines a range using two fields, instead of the native
  142. PostgreSQL range types, you should write an expression that uses the equivalent
  143. function (e.g. ``TsTzRange()``), and use the delimiters for the field. Most
  144. often, the delimiters will be ``'[)'``, meaning that the lower bound is
  145. inclusive and the upper bound is exclusive. You may use the
  146. :class:`~django.contrib.postgres.fields.RangeBoundary` that provides an
  147. expression mapping for the `range boundaries <https://www.postgresql.org/docs/
  148. current/rangetypes.html#RANGETYPES-INCLUSIVITY>`_. For example::
  149. from django.contrib.postgres.constraints import ExclusionConstraint
  150. from django.contrib.postgres.fields import (
  151. DateTimeRangeField,
  152. RangeBoundary,
  153. RangeOperators,
  154. )
  155. from django.db import models
  156. from django.db.models import Func, Q
  157. class TsTzRange(Func):
  158. function = 'TSTZRANGE'
  159. output_field = DateTimeRangeField()
  160. class Reservation(models.Model):
  161. room = models.ForeignKey('Room', on_delete=models.CASCADE)
  162. start = models.DateTimeField()
  163. end = models.DateTimeField()
  164. cancelled = models.BooleanField(default=False)
  165. class Meta:
  166. constraints = [
  167. ExclusionConstraint(
  168. name='exclude_overlapping_reservations',
  169. expressions=(
  170. (TsTzRange('start', 'end', RangeBoundary()), RangeOperators.OVERLAPS),
  171. ('room', RangeOperators.EQUAL),
  172. ),
  173. condition=Q(cancelled=False),
  174. ),
  175. ]