| 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:: |
| 30 |
|
| 31 |
CheckConstraint(condition=Q(age__gte=18), name="%(app_label)s_%(class)s_is_adult") |
| 32 |
|
| 33 |
.. admonition:: Validation of Constraints |
| 34 |
|
| 35 |
Constraints are checked during the :ref:`model validation |
| 36 |
<validating-objects>`. |
| 37 |
|
| 38 |
``BaseConstraint`` |
| 39 |
================== |
| 40 |
|
| 41 |
.. class:: BaseConstraint(* name, violation_error_code=None, violation_error_message=None) |
| 42 |
|
| 43 |
Base class for all constraints. Subclasses must implement |
| 44 |
``constraint_sql()``, ``create_sql()``, ``remove_sql()`` and |
| 45 |
``validate()`` methods. |
| 46 |
|
| 47 |
.. deprecated:: 5.0 |
| 48 |
|
| 49 |
Support for passing positional arguments is deprecated. |
| 50 |
|
| 51 |
All constraints have the following parameters in common: |
| 52 |
|
| 53 |
``name`` |
| 54 |
-------- |
| 55 |
|
| 56 |
.. attribute:: BaseConstraint.name |
| 57 |
|
| 58 |
The name of the constraint. You must always specify a unique name for the |
| 59 |
constraint. |
| 60 |
|
| 61 |
``violation_error_code`` |
| 62 |
------------------------ |
| 63 |
|
| 64 |
.. attribute:: BaseConstraint.violation_error_code |
| 65 |
|
| 66 |
The error code used when ``ValidationError`` is raised during |
| 67 |
:ref:`model validation <validating-objects>`. Defaults to ``None``. |
| 68 |
|
| 69 |
``violation_error_message`` |
| 70 |
--------------------------- |
| 71 |
|
| 72 |
.. attribute:: BaseConstraint.violation_error_message |
| 73 |
|
| 74 |
The error message used when ``ValidationError`` is raised during |
| 75 |
:ref:`model validation <validating-objects>`. Defaults to |
| 76 |
``"Constraint ā%(name)sā is violated."``. |
| 77 |
|
| 78 |
``validate()`` |
| 79 |
-------------- |
| 80 |
|
| 81 |
.. method:: BaseConstraint.validate(model, instance, exclude=None, using=DEFAULT_DB_ALIAS) |
| 82 |
|
| 83 |
Validates that the constraint, defined on ``model``, is respected on the |
| 84 |
``instance``. This will do a query on the database to ensure that the |
| 85 |
constraint is respected. If fields in the ``exclude`` list are needed to |
| 86 |
validate the constraint, the constraint is ignored. |
| 87 |
|
| 88 |
Raise a ``ValidationError`` if the constraint is violated. |
| 89 |
|
| 90 |
This method must be implemented by a subclass. |
| 91 |
|
| 92 |
``CheckConstraint`` |
| 93 |
=================== |
| 94 |
|
| 95 |
.. class:: CheckConstraint(*, condition, name, violation_error_code=None, violation_error_message=None) |
| 96 |
|
| 97 |
Creates a check constraint in the database. |
| 98 |
|
| 99 |
``condition`` |
| 100 |
------------- |
| 101 |
|
| 102 |
.. attribute:: CheckConstraint.condition |
| 103 |
|
| 104 |
A :class:`Q` object or boolean :class:`~django.db.models.Expression` that |
| 105 |
specifies the conditional check you want the constraint to enforce. |
| 106 |
|
| 107 |
For example:: |
| 108 |
|
| 109 |
CheckConstraint(condition=Q(age__gte=18), name="age_gte_18") |
| 110 |
|
| 111 |
ensures the age field is never less than 18. |
| 112 |
|
| 113 |
.. admonition:: Expression order |
| 114 |
|
| 115 |
``Q`` argument order is not necessarily preserved, however the order of |
| 116 |
``Q`` expressions themselves are preserved. This may be important for |
| 117 |
databases that preserve check constraint expression order for performance |
| 118 |
reasons. For example, use the following format if order matters:: |
| 119 |
|
| 120 |
CheckConstraint( |
| 121 |
condition=Q(age__gte=18) & Q(expensive_check=condition), |
| 122 |
name="age_gte_18_and_others", |
| 123 |
) |
| 124 |
|
| 125 |
.. admonition:: Oracle < 23c |
| 126 |
|
| 127 |
Checks with nullable fields on Oracle < 23c must include a condition |
| 128 |
allowing for ``NULL`` values in order for :meth:`~BaseConstraint.validate` |
| 129 |
to behave the same as check constraints validation. For example, if ``age`` |
| 130 |
is a nullable field:: |
| 131 |
|
| 132 |
CheckConstraint(condition=Q(age__gte=18) | Q(age__isnull=True), name="age_gte_18") |
| 133 |
|
| 134 |
.. deprecated:: 5.1 |
| 135 |
|
| 136 |
The ``check`` attribute is deprecated in favor of ``condition``. |
| 137 |
|
| 138 |
``UniqueConstraint`` |
| 139 |
==================== |
| 140 |
|
| 141 |
.. class:: UniqueConstraint(*expressions, fields=(), name=None, condition=None, deferrable=None, include=None, opclasses=(), nulls_distinct=None, violation_error_code=None, violation_error_message=None) |
| 142 |
|
| 143 |
Creates a unique constraint in the database. |
| 144 |
|
| 145 |
``expressions`` |
| 146 |
--------------- |
| 147 |
|
| 148 |
.. attribute:: UniqueConstraint.expressions |
| 149 |
|
| 150 |
Positional argument ``*expressions`` allows creating functional unique |
| 151 |
constraints on expressions and database functions. |
| 152 |
|
| 153 |
For example:: |
| 154 |
|
| 155 |
UniqueConstraint(Lower("name").desc(), "category", name="unique_lower_name_category") |
| 156 |
|
| 157 |
creates a unique constraint on the lowercased value of the ``name`` field in |
| 158 |
descending order and the ``category`` field in the default ascending order. |
| 159 |
|
| 160 |
Functional unique constraints have the same database restrictions as |
| 161 |
:attr:`Index.expressions`. |
| 162 |
|
| 163 |
``fields`` |
| 164 |
---------- |
| 165 |
|
| 166 |
.. attribute:: UniqueConstraint.fields |
| 167 |
|
| 168 |
A list of field names that specifies the unique set of columns you want the |
| 169 |
constraint to enforce. |
| 170 |
|
| 171 |
For example:: |
| 172 |
|
| 173 |
UniqueConstraint(fields=["room", "date"], name="unique_booking") |
| 174 |
|
| 175 |
ensures each room can only be booked once for each date. |
| 176 |
|
| 177 |
``condition`` |
| 178 |
------------- |
| 179 |
|
| 180 |
.. attribute:: UniqueConstraint.condition |
| 181 |
|
| 182 |
A :class:`Q` object that specifies the condition you want the constraint to |
| 183 |
enforce. |
| 184 |
|
| 185 |
For example:: |
| 186 |
|
| 187 |
UniqueConstraint(fields=["user"], condition=Q(status="DRAFT"), name="unique_draft_user") |
| 188 |
|
| 189 |
ensures that each user only has one draft. |
| 190 |
|
| 191 |
These conditions have the same database restrictions as |
| 192 |
:attr:`Index.condition`. |
| 193 |
|
| 194 |
``deferrable`` |
| 195 |
-------------- |
| 196 |
|
| 197 |
.. attribute:: UniqueConstraint.deferrable |
| 198 |
|
| 199 |
Set this parameter to create a deferrable unique constraint. Accepted values |
| 200 |
are ``Deferrable.DEFERRED`` or ``Deferrable.IMMEDIATE``. For example:: |
| 201 |
|
| 202 |
from django.db.models import Deferrable, UniqueConstraint |
| 203 |
|
| 204 |
UniqueConstraint( |
| 205 |
name="unique_order", |
| 206 |
fields=["order"], |
| 207 |
deferrable=Deferrable.DEFERRED, |
| 208 |
) |
| 209 |
|
| 210 |
By default constraints are not deferred. A deferred constraint will not be |
| 211 |
enforced until the end of the transaction. An immediate constraint will be |
| 212 |
enforced immediately after every command. |
| 213 |
|
| 214 |
.. admonition:: MySQL, MariaDB, and SQLite. |
| 215 |
|
| 216 |
Deferrable unique constraints are ignored on MySQL, MariaDB, and SQLite as |
| 217 |
they do not support them. |
| 218 |
|
| 219 |
.. warning:: |
| 220 |
|
| 221 |
Deferred unique constraints may lead to a `performance penalty |
| 222 |
<https://www.postgresql.org/docs/current/sql-createtable.html#id-1.9.3.85.9.4>`_. |
| 223 |
|
| 224 |
``include`` |
| 225 |
----------- |
| 226 |
|
| 227 |
.. attribute:: UniqueConstraint.include |
| 228 |
|
| 229 |
A list or tuple of the names of the fields to be included in the covering |
| 230 |
unique index as non-key columns. This allows index-only scans to be used for |
| 231 |
queries that select only included fields (:attr:`~UniqueConstraint.include`) |
| 232 |
and filter only by unique fields (:attr:`~UniqueConstraint.fields`). |
| 233 |
|
| 234 |
For example:: |
| 235 |
|
| 236 |
UniqueConstraint(name="unique_booking", fields=["room", "date"], include=["full_name"]) |
| 237 |
|
| 238 |
will allow filtering on ``room`` and ``date``, also selecting ``full_name``, |
| 239 |
while fetching data only from the index. |
| 240 |
|
| 241 |
Unique constraints with non-key columns are ignored for databases besides |
| 242 |
PostgreSQL. |
| 243 |
|
| 244 |
Non-key columns have the same database restrictions as :attr:`Index.include`. |
| 245 |
|
| 246 |
|
| 247 |
``opclasses`` |
| 248 |
------------- |
| 249 |
|
| 250 |
.. attribute:: UniqueConstraint.opclasses |
| 251 |
|
| 252 |
The names of the `PostgreSQL operator classes |
| 253 |
<https://www.postgresql.org/docs/current/indexes-opclass.html>`_ to use for |
| 254 |
this unique index. If you require a custom operator class, you must provide one |
| 255 |
for each field in the index. |
| 256 |
|
| 257 |
For example:: |
| 258 |
|
| 259 |
UniqueConstraint( |
| 260 |
name="unique_username", fields=["username"], opclasses=["varchar_pattern_ops"] |
| 261 |
) |
| 262 |
|
| 263 |
creates a unique index on ``username`` using ``varchar_pattern_ops``. |
| 264 |
|
| 265 |
``opclasses`` are ignored for databases besides PostgreSQL. |
| 266 |
|
| 267 |
``nulls_distinct`` |
| 268 |
------------------ |
| 269 |
|
| 270 |
.. attribute:: UniqueConstraint.nulls_distinct |
| 271 |
|
| 272 |
Whether rows containing ``NULL`` values covered by the unique constraint should |
| 273 |
be considered distinct from each other. The default value is ``None`` which |
| 274 |
uses the database default which is ``True`` on most backends. |
| 275 |
|
| 276 |
For example:: |
| 277 |
|
| 278 |
UniqueConstraint(name="ordering", fields=["ordering"], nulls_distinct=False) |
| 279 |
|
| 280 |
creates a unique constraint that only allows one row to store a ``NULL`` value |
| 281 |
in the ``ordering`` column. |
| 282 |
|
| 283 |
Unique constraints with ``nulls_distinct`` are ignored for databases besides |
| 284 |
PostgreSQL 15+. |
| 285 |
|
| 286 |
``violation_error_code`` |
| 287 |
------------------------ |
| 288 |
|
| 289 |
.. attribute:: UniqueConstraint.violation_error_code |
| 290 |
|
| 291 |
The error code used when a ``ValidationError`` is raised during |
| 292 |
:ref:`model validation <validating-objects>`. |
| 293 |
|
| 294 |
Defaults to :attr:`.BaseConstraint.violation_error_code`, when either |
| 295 |
:attr:`.UniqueConstraint.condition` is set or :attr:`.UniqueConstraint.fields` |
| 296 |
is not set. |
| 297 |
|
| 298 |
If :attr:`.UniqueConstraint.fields` is set without a |
| 299 |
:attr:`.UniqueConstraint.condition`, defaults to the :attr:`Meta.unique_together |
| 300 |
<django.db.models.Options.unique_together>` error code when there are multiple |
| 301 |
fields, and to the :attr:`.Field.unique` error code when there is a single |
| 302 |
field. |
| 303 |
|
| 304 |
.. versionchanged:: 5.2 |
| 305 |
|
| 306 |
In older versions, the provided |
| 307 |
:attr:`.UniqueConstraint.violation_error_code` was not used when |
| 308 |
:attr:`.UniqueConstraint.fields` was set without a |
| 309 |
:attr:`.UniqueConstraint.condition`. |
| 310 |
|
| 311 |
``violation_error_message`` |
| 312 |
--------------------------- |
| 313 |
|
| 314 |
.. attribute:: UniqueConstraint.violation_error_message |
| 315 |
|
| 316 |
The error message used when a ``ValidationError`` is raised during |
| 317 |
:ref:`model validation <validating-objects>`. |
| 318 |
|
| 319 |
Defaults to :attr:`.BaseConstraint.violation_error_message`, when either |
| 320 |
:attr:`.UniqueConstraint.condition` is set or :attr:`.UniqueConstraint.fields` |
| 321 |
is not set. |
| 322 |
|
| 323 |
If :attr:`.UniqueConstraint.fields` is set without a |
| 324 |
:attr:`.UniqueConstraint.condition`, defaults to the :attr:`Meta.unique_together |
| 325 |
<django.db.models.Options.unique_together>` error message when there are |
| 326 |
multiple fields, and to the :attr:`.Field.unique` error message when there is a |
| 327 |
single field. |
| 328 |
|
| 329 |
.. versionchanged:: 5.2 |
| 330 |
|
| 331 |
In older versions, the provided |
| 332 |
:attr:`.UniqueConstraint.violation_error_message` was not used when |
| 333 |
:attr:`.UniqueConstraint.fields` was set without a |
| 334 |
:attr:`.UniqueConstraint.condition`. |