约束参考Link to this heading

本模块中定义的类可以创建数据库约束。它们被添加到模型中 Meta.constraints 选项中。

BaseConstraintLink to this heading

class BaseConstraint(name, violation_error_message=None)Link to this definition

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

All constraints have the following parameters in common:

nameLink to this heading

BaseConstraint.nameLink to this definition

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

violation_error_messageLink to this heading

BaseConstraint.violation_error_messageLink to this definition

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

validate()Link to this heading

BaseConstraint.validate(model, instance, exclude=None, using=DEFAULT_DB_ALIAS)Link to this definition

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.

CheckConstraintLink to this heading

class CheckConstraint(*, check, name, violation_error_message=None)Link to this definition

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

checkLink to this heading

CheckConstraint.checkLink to this definition

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

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

UniqueConstraintLink to this heading

class UniqueConstraint(*expressions, fields=(), name=None, condition=None, deferrable=None, include=None, opclasses=(), violation_error_message=None)Link to this definition

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

expressionsLink to this heading

UniqueConstraint.expressionsLink to this definition

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

例子:

Code
UniqueConstraint(Lower('name').desc(), 'category', name='unique_lower_name_category')

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.

fieldsLink to this heading

UniqueConstraint.fieldsLink to this definition

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

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

conditionLink to this heading

UniqueConstraint.conditionLink to this definition

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

例子:

Code
UniqueConstraint(fields=['user'], condition=Q(status='DRAFT'), name='unique_draft_user')

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

这些条件与 Index.condition 具有相同的数据库限制。

deferrableLink to this heading

UniqueConstraint.deferrableLink to this definition

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

Code
from django.db.models import Deferrable, UniqueConstraint

UniqueConstraint(
    name='unique_order',
    fields=['order'],
    deferrable=Deferrable.DEFERRED,
)

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

includeLink to this heading

UniqueConstraint.includeLink to this definition

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

例子:

Code
UniqueConstraint(name='unique_booking', fields=['room', 'date'], include=['full_name'])

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

include 只在 PostgreSQL 上支持。

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

opclassesLink to this heading

UniqueConstraint.opclassesLink to this definition

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

例子:

Code
UniqueConstraint(name='unique_username', fields=['username'], opclasses=['varchar_pattern_ops'])

creates a unique index on username using varchar_pattern_ops.

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

violation_error_messageLink to this heading

UniqueConstraint.violation_error_messageLink to this definition

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

This message is not used for UniqueConstraints with fields and without a condition. Such UniqueConstraints show the same message as constraints defined with Field.unique or in Meta.unique_together.