constraints.txt 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212
  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. ``index_type``
  41. --------------
  42. .. attribute:: ExclusionConstraint.index_type
  43. The index type of the constraint. Accepted values are ``GIST`` or ``SPGIST``.
  44. Matching is case insensitive. If not provided, the default index type is
  45. ``GIST``.
  46. ``condition``
  47. -------------
  48. .. attribute:: ExclusionConstraint.condition
  49. A :class:`~django.db.models.Q` object that specifies the condition to restrict
  50. a constraint to a subset of rows. For example,
  51. ``condition=Q(cancelled=False)``.
  52. These conditions have the same database restrictions as
  53. :attr:`django.db.models.Index.condition`.
  54. ``deferrable``
  55. --------------
  56. .. attribute:: ExclusionConstraint.deferrable
  57. Set this parameter to create a deferrable exclusion constraint. Accepted values
  58. are ``Deferrable.DEFERRED`` or ``Deferrable.IMMEDIATE``. For example::
  59. from django.contrib.postgres.constraints import ExclusionConstraint
  60. from django.contrib.postgres.fields import RangeOperators
  61. from django.db.models import Deferrable
  62. ExclusionConstraint(
  63. name='exclude_overlapping_deferred',
  64. expressions=[
  65. ('timespan', RangeOperators.OVERLAPS),
  66. ],
  67. deferrable=Deferrable.DEFERRED,
  68. )
  69. By default constraints are not deferred. A deferred constraint will not be
  70. enforced until the end of the transaction. An immediate constraint will be
  71. enforced immediately after every command.
  72. .. warning::
  73. Deferred exclusion constraints may lead to a `performance penalty
  74. <https://www.postgresql.org/docs/current/sql-createtable.html#id-1.9.3.85.9.4>`_.
  75. ``include``
  76. -----------
  77. .. attribute:: ExclusionConstraint.include
  78. A list or tuple of the names of the fields to be included in the covering
  79. exclusion constraint as non-key columns. This allows index-only scans to be
  80. used for queries that select only included fields
  81. (:attr:`~ExclusionConstraint.include`) and filter only by indexed fields
  82. (:attr:`~ExclusionConstraint.expressions`).
  83. ``include`` is supported only for GiST indexes on PostgreSQL 12+.
  84. ``opclasses``
  85. -------------
  86. .. attribute:: ExclusionConstraint.opclasses
  87. The names of the `PostgreSQL operator classes
  88. <https://www.postgresql.org/docs/current/indexes-opclass.html>`_ to use for
  89. this constraint. If you require a custom operator class, you must provide one
  90. for each expression in the constraint.
  91. For example::
  92. ExclusionConstraint(
  93. name='exclude_overlapping_opclasses',
  94. expressions=[('circle', RangeOperators.OVERLAPS)],
  95. opclasses=['circle_ops'],
  96. )
  97. creates an exclusion constraint on ``circle`` using ``circle_ops``.
  98. Examples
  99. --------
  100. The following example restricts overlapping reservations in the same room, not
  101. taking canceled reservations into account::
  102. from django.contrib.postgres.constraints import ExclusionConstraint
  103. from django.contrib.postgres.fields import DateTimeRangeField, RangeOperators
  104. from django.db import models
  105. from django.db.models import Q
  106. class Room(models.Model):
  107. number = models.IntegerField()
  108. class Reservation(models.Model):
  109. room = models.ForeignKey('Room', on_delete=models.CASCADE)
  110. timespan = DateTimeRangeField()
  111. cancelled = models.BooleanField(default=False)
  112. class Meta:
  113. constraints = [
  114. ExclusionConstraint(
  115. name='exclude_overlapping_reservations',
  116. expressions=[
  117. ('timespan', RangeOperators.OVERLAPS),
  118. ('room', RangeOperators.EQUAL),
  119. ],
  120. condition=Q(cancelled=False),
  121. ),
  122. ]
  123. In case your model defines a range using two fields, instead of the native
  124. PostgreSQL range types, you should write an expression that uses the equivalent
  125. function (e.g. ``TsTzRange()``), and use the delimiters for the field. Most
  126. often, the delimiters will be ``'[)'``, meaning that the lower bound is
  127. inclusive and the upper bound is exclusive. You may use the
  128. :class:`~django.contrib.postgres.fields.RangeBoundary` that provides an
  129. expression mapping for the `range boundaries <https://www.postgresql.org/docs/
  130. current/rangetypes.html#RANGETYPES-INCLUSIVITY>`_. For example::
  131. from django.contrib.postgres.constraints import ExclusionConstraint
  132. from django.contrib.postgres.fields import (
  133. DateTimeRangeField,
  134. RangeBoundary,
  135. RangeOperators,
  136. )
  137. from django.db import models
  138. from django.db.models import Func, Q
  139. class TsTzRange(Func):
  140. function = 'TSTZRANGE'
  141. output_field = DateTimeRangeField()
  142. class Reservation(models.Model):
  143. room = models.ForeignKey('Room', on_delete=models.CASCADE)
  144. start = models.DateTimeField()
  145. end = models.DateTimeField()
  146. cancelled = models.BooleanField(default=False)
  147. class Meta:
  148. constraints = [
  149. ExclusionConstraint(
  150. name='exclude_overlapping_reservations',
  151. expressions=(
  152. (TsTzRange('start', 'end', RangeBoundary()), RangeOperators.OVERLAPS),
  153. ('room', RangeOperators.EQUAL),
  154. ),
  155. condition=Q(cancelled=False),
  156. ),
  157. ]