Fixed #11964 -- Added support for database check constraints.

This commit is contained in:
Ian Foote 2016-11-05 13:12:12 +00:00 committed by Tim Graham
parent 6fbfb5cb96
commit 952f05a6db
29 changed files with 799 additions and 39 deletions

View file

@ -0,0 +1,46 @@
===========================
Check constraints reference
===========================
.. module:: django.db.models.constraints
.. currentmodule:: django.db.models
.. versionadded:: 2.2
The ``CheckConstraint`` class creates database check constraints. They are
added in the model :attr:`Meta.constraints
<django.db.models.Options.constraints>` option. This document
explains the API references of :class:`CheckConstraint`.
.. admonition:: Referencing built-in constraints
Constraints are defined in ``django.db.models.constraints``, but for
convenience they're imported into :mod:`django.db.models`. The standard
convention is to use ``from django.db import models`` and refer to the
constraints as ``models.CheckConstraint``.
``CheckConstraint`` options
===========================
.. class:: CheckConstraint(constraint, name)
Creates a check constraint in the database.
``constraint``
--------------
.. attribute:: CheckConstraint.constraint
A :class:`Q` object that specifies the condition you want the constraint to
enforce.
For example ``CheckConstraint(Q(age__gte=18), 'age_gte_18')`` ensures the age
field is never less than 18.
``name``
--------
.. attribute:: CheckConstraint.name
The name of the constraint.

View file

@ -9,6 +9,7 @@ Model API reference. For introductory material, see :doc:`/topics/db/models`.
fields
indexes
check-constraints
meta
relations
class

View file

@ -451,6 +451,26 @@ Django quotes column and table names behind the scenes.
index_together = ["pub_date", "deadline"]
``constraints``
---------------
.. attribute:: Options.constraints
.. versionadded:: 2.2
A list of :doc:`constraints </ref/models/check-constraints>` that you want
to define on the model::
from django.db import models
class Customer(models.Model):
age = models.IntegerField()
class Meta:
constraints = [
models.CheckConstraint(models.Q(age__gte=18), 'age_gte_18'),
]
``verbose_name``
----------------