constraints.txt 5.8 KB

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