约束参考

    引用内置约束

    约束是在 django.db.models.constraint 中定义的,但为了方便,它们被导入到 django.db.models 中。标准的惯例是使用 from django.db import models 作为 models.<Foo>Constraint

    抽象基类中的约束

    你必须始终为约束指定一个唯一的名称。因此,你通常不能在抽象基类上指定一个约束,因为 Meta.craces 选项是由子类继承的,每次的属性值(包括 name)都完全相同。为了解决名称碰撞的问题,名称的一部分可能包含 '%(app_label)s''%(class)s',它们分别被具体模型的小写应用标签和类名所代替。例如 CheckConstraint(check=Q(age__gte=18),name='%(app_label)s_%(class)s_is_adult')

    约束的验证

    Constraints are checked during the .

    Changed in Django 4.1:

    In older versions, constraints were not checked during model validation.

    class BaseConstraint(name, violation_error_message=None)

    Base class for all constraints. Subclasses must implement , create_sql(), remove_sql() and validate() methods.

    All constraints have the following parameters in common:

    BaseConstraint.name

    约束的名称。你必须始终为约束指定一个唯一的名称。

    violation_error_message

    New in Django 4.1.

    BaseConstraint.violation_error_message

    The error message used when ValidationError is raised during . Defaults to "Constraint “%(name)s” is violated.".

    validate()

    New in Django 4.1.

    BaseConstraint.validate(model, instance, exclude=None, using=DEFAULT_DB_ALIAS)

    Validates that the constraint, defined on model, is respected on the instance. This will do a query on the database to ensure that the constraint is respected. If fields in the exclude list are needed to validate the constraint, the constraint is ignored.

    Raise a ValidationError if the constraint is violated.

    This method must be implemented by a subclass.

    在数据库中创建一个检查约束

    CheckConstraint.check

    一个 对象或布尔值 Expression,它指定了你要强制约束的检查。

    例如,CheckConstraint(check=Q(age__gte=18), name='age_gte_18') 确保年龄字段永远不小于 18。

    Changed in Django 4.1:

    The violation_error_message argument was added.

    class UniqueConstraint(\expressions, fields=(), name=None, condition=None, deferrable=None, include=None, opclasses=(), violation_error_message=None*)

    在数据库中创建一个唯一约束。

    expressions

    New in Django 4.0.

    Positional argument *expressions allows creating functional unique constraints on expressions and database functions.

    例子:

    creates a unique constraint on the lowercased value of the name field in descending order and the category field in the default ascending order.

    Functional unique constraints have the same database restrictions as Index.expressions.

    fields

    UniqueConstraint.fields

    一个字段名的列表,它指定了你要强制约束的唯一列集。

    例如,UniqueConstraint(field=['room', 'date'], name='unique_booking') 确保每个房间在每个日期只能被预订一次。

    UniqueConstraint.condition

    一个 Q 对象,用于指定你想要强制执行的约束条件。

    例子:

    确保每个用户只有一份草稿。

    deferrable

    UniqueConstraint.deferrable

    设置该参数,可创建一个可推迟的唯一约束。接受的值是 Deferrable.DEFERREDDeferrable.IMMEDIATE。例如:

    默认情况下,约束条件是不推迟的。推迟的约束条件在事务结束前不会被强制执行。即时约束将在每条命令后立即执行。

    MySQL,MariaDB 和 SQLite。

    在 MySQL、MariaDB 和 SQLite 上,可推迟的唯一约束被忽略,因为它们都不支持。

    警告

    推迟的唯一约束可能导致 性能惩罚

    include

    UniqueConstraint.include

    一个包含在覆盖的唯一索引中的字段名称的列表或元组,作为非键列。这允许只用索引扫描,用于只选择包含的字段( include )和只过滤唯一字段( )的查询。

    例子:

    将允许对 roomdate 进行过滤,也可以选择 full_name,同时只从索引中获取数据。

    include 只在 PostgreSQL 上支持。

    Non-key columns have the same database restrictions as Index.include.

    UniqueConstraint.opclasses

    The names of the to use for this unique index. If you require a custom operator class, you must provide one for each field in the index.

    例子:

    creates a unique index on username using varchar_pattern_ops.

    opclasses 对于 PostgreSQL 以外的数据库来说是被忽略的。

    violation_error_message

    New in Django 4.1.

    The error message used when ValidationError is raised during . Defaults to BaseConstraint.violation_error_message.