Constraints reference
The classes defined in this module create database constraints. They are addedin the model option.
Referencing built-in constraints
Constraints are defined in django.db.models.constraints
, but forconvenience they’re imported into . The standardconvention is to use from django.db import models
and refer to theconstraints as models.<Foo>Constraint
.
Constraints in abstract base classes
Validation of Constraints
In general constraints are not checked during full_clean()
, and donot raise ValidationError
s. Rather you’ll get a database integrityerror on save()
. s without acondition
(i.e. non-partial unique constraints)are different in this regard, in that they leverage the existingvalidate_unique()
logic, and thus enable two-stage validation. Inaddition to IntegrityError
on save()
, ValidationError
is alsoraised during model validation when the UniqueConstraint
is violated.
- class
CheckConstraint
(*, check, name) - Creates a check constraint in the database.
For example, CheckConstraint(check=Q(age__gte=18), name='age_gte_18')
ensures the age field is never less than 18.
Changed in Django 3.0:Interpolation of and '%(class)s'
was added.
UniqueConstraint
- Creates a unique constraint in the database.
UniqueConstraint.
fields
- A list of field names that specifies the unique set of columns you want theconstraint to enforce.
UniqueConstraint.
name
- The name of the constraint.
Changed in Django 3.0:Interpolation of '%(app_label)s'
and '%(class)s'
was added.
For example:
ensures that each user only has one draft.
These conditions have the same database restrictions as.