“Django/docs/3.0.x/ref/contrib/postgres/constraints”的版本间差异

来自菜鸟教程
Django/docs/3.0.x/ref/contrib/postgres/constraints
跳转至:导航、​搜索
(autoload)
 
(Page commit)
 
第1行: 第1行:
 +
{{DISPLAYTITLE:PostgreSQL 特定的数据库约束 — Django 文档}}
 
<div id="module-django.contrib.postgres.constraints" class="section">
 
<div id="module-django.contrib.postgres.constraints" class="section">
  
 
<span id="postgresql-specific-database-constraints"></span>
 
<span id="postgresql-specific-database-constraints"></span>
= PostgreSQL specific database constraints =
+
= PostgreSQL 特定的数据库约束 =
  
PostgreSQL supports additional data integrity constraints available from the
+
PostgreSQL 支持来自 <code>django.contrib.postgres.constraints</code> 模块的额外数据完整性约束。 它们被添加到模型 [[../../../models/options#django.db.models.Options|Meta.constraints]] 选项中。
<code>django.contrib.postgres.constraints</code> module. They are added in the model
 
[[../../../models/options#django.db.models.Options|<code>Meta.constraints</code>]] option.
 
  
 
<div id="exclusionconstraint" class="section">
 
<div id="exclusionconstraint" class="section">
  
== <code>ExclusionConstraint</code> ==
+
== ExclusionConstraint ==
  
 
<div class="versionadded">
 
<div class="versionadded">
  
 +
<span class="versionmodified added">3.0 版中的新功能。</span>
  
  
 
</div>
 
</div>
 
<dl>
 
<dl>
<dt>''class'' <code>ExclusionConstraint</code><span class="sig-paren">(</span>''<span class="o">*</span>'', ''<span class="n">name</span>'', ''<span class="n">expressions</span>'', ''<span class="n">index_type</span><span class="o">=</span><span class="default_value">None</span>'', ''<span class="n">condition</span><span class="o">=</span><span class="default_value">None</span>''<span class="sig-paren">)</span></dt>
+
<dt>''<span class="pre">class</span>'' <span class="sig-name descname"><span class="pre">ExclusionConstraint</span></span><span class="sig-paren">(</span>''<span class="o"><span class="pre">*</span></span>'', ''<span class="n"><span class="pre">name</span></span>'', ''<span class="n"><span class="pre">expressions</span></span>'', ''<span class="n"><span class="pre">index_type</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span>'', ''<span class="n"><span class="pre">condition</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span>''<span class="sig-paren">)</span></dt>
<dd><p>Creates an exclusion constraint in the database. Internally, PostgreSQL
+
<dd><p>在数据库中创建排除约束。 在内部,PostgreSQL 使用索引实现排除约束。 默认索引类型为 [https://www.postgresql.org/docs/current/gist.html GiST]。 要使用它们,您需要在 PostgreSQL 上激活 [https://www.postgresql.org/docs/current/btree-gist.html btree_gist 扩展] 。 您可以使用 [[../operations#django.contrib.postgres.operations|BtreeGistExtension]] 迁移操作安装它。</p>
implements exclusion constraints using indexes. The default index type is
+
<p>如果您尝试插入与现有行冲突的新行,则会引发 [[../../../exceptions#django.db|IntegrityError]]。 同样,当更新与现有行冲突时。</p></dd></dl>
[https://www.postgresql.org/docs/current/gist.html GiST]. To use them,
 
you need to activate the [https://www.postgresql.org/docs/current/btree-gist.html btree_gist extension] on PostgreSQL.
 
You can install it using the
 
[[../operations#django.contrib.postgres.operations|<code>BtreeGistExtension</code>]] migration
 
operation.</p>
 
<p>If you attempt to insert a new row that conflicts with an existing row, an
 
[[../../../exceptions#django.db|<code>IntegrityError</code>]] is raised. Similarly, when update
 
conflicts with an existing row.</p></dd></dl>
 
  
 
<div id="name" class="section">
 
<div id="name" class="section">
  
=== <code>name</code> ===
+
=== name ===
  
; <code>ExclusionConstraint.</code><code>name</code>
+
; <span class="sig-prename descclassname"><span class="pre">ExclusionConstraint.</span></span><span class="sig-name descname"><span class="pre">name</span></span>
 
:  
 
:  
  
The name of the constraint.
+
约束的名称。
  
  
第43行: 第35行:
 
<div id="expressions" class="section">
 
<div id="expressions" class="section">
  
=== <code>expressions</code> ===
+
=== expressions ===
  
; <code>ExclusionConstraint.</code><code>expressions</code>
+
; <span class="sig-prename descclassname"><span class="pre">ExclusionConstraint.</span></span><span class="sig-name descname"><span class="pre">expressions</span></span>
 
:  
 
:  
  
An iterable of 2-tuples. The first element is an expression or string. The
+
一个 2 元组的可迭代对象。 第一个元素是表达式或字符串。 第二个元素是表示为字符串的 SQL 运算符。 为避免拼写错误,您可以使用 [[../fields#django.contrib.postgres.fields|RangeOperators]] 将运算符映射到字符串。 例如:
second element is an SQL operator represented as a string. To avoid typos, you
 
may use [[../fields#django.contrib.postgres.fields|<code>RangeOperators</code>]] which maps the
 
operators with strings. For example:
 
  
 
<div class="highlight-default notranslate">
 
<div class="highlight-default notranslate">
第57行: 第46行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>expressions=[
+
<syntaxhighlight lang="python">expressions=[
 
     ('timespan', RangeOperators.ADJACENT_TO),
 
     ('timespan', RangeOperators.ADJACENT_TO),
 
     (F('room'), RangeOperators.EQUAL),
 
     (F('room'), RangeOperators.EQUAL),
]</pre>
+
]</syntaxhighlight>
  
 
</div>
 
</div>
第67行: 第56行:
 
<div class="admonition-restrictions-on-operators admonition">
 
<div class="admonition-restrictions-on-operators admonition">
  
Restrictions on operators.
+
对运营商的限制。
  
Only commutative operators can be used in exclusion constraints.
+
在排除约束中只能使用交换运算符。
  
  
第77行: 第66行:
 
<div id="index-type" class="section">
 
<div id="index-type" class="section">
  
=== <code>index_type</code> ===
+
=== index_type ===
  
; <code>ExclusionConstraint.</code><code>index_type</code>
+
; <span class="sig-prename descclassname"><span class="pre">ExclusionConstraint.</span></span><span class="sig-name descname"><span class="pre">index_type</span></span>
 
:  
 
:  
  
The index type of the constraint. Accepted values are <code>GIST</code> or <code>SPGIST</code>.
+
约束的索引类型。 可接受的值为 <code>GIST</code> <code>SPGIST</code>。 匹配不区分大小写。 如果未提供,则默认索引类型为 <code>GIST</code>
Matching is case insensitive. If not provided, the default index type is
 
<code>GIST</code>.
 
  
  
第90行: 第77行:
 
<div id="condition" class="section">
 
<div id="condition" class="section">
  
=== <code>condition</code> ===
+
=== condition ===
  
; <code>ExclusionConstraint.</code><code>condition</code>
+
; <span class="sig-prename descclassname"><span class="pre">ExclusionConstraint.</span></span><span class="sig-name descname"><span class="pre">condition</span></span>
 
:  
 
:  
  
A [[../../../models/querysets#django.db.models|<code>Q</code>]] object that specifies the condition to restrict
+
一个 [[../../../models/querysets#django.db.models|Q]] 对象,它指定将约束限制为行子集的条件。 例如,<code>condition=Q(cancelled=False)</code>
a constraint to a subset of rows. For example,
 
<code>condition=Q(cancelled=False)</code>.
 
  
These conditions have the same database restrictions as
+
这些条件与 [[../../../models/indexes#django.db.models.Index|django.db.models.Index.condition]] 具有相同的数据库限制。
[[../../../models/indexes#django.db.models.Index|<code>django.db.models.Index.condition</code>]].
 
  
  
第106行: 第90行:
 
<div id="examples" class="section">
 
<div id="examples" class="section">
  
=== 示例 ===
+
=== 例子 ===
  
The following example restricts overlapping reservations in the same room, not
+
以下示例限制同一房间内的重叠预订,不考虑取消的预订:
taking canceled reservations into account:
 
  
 
<div class="highlight-default notranslate">
 
<div class="highlight-default notranslate">
第115行: 第98行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>from django.contrib.postgres.constraints import ExclusionConstraint
+
<syntaxhighlight lang="python">from django.contrib.postgres.constraints import ExclusionConstraint
 
from django.contrib.postgres.fields import DateTimeRangeField, RangeOperators
 
from django.contrib.postgres.fields import DateTimeRangeField, RangeOperators
 
from django.db import models
 
from django.db import models
第139行: 第122行:
 
                 condition=Q(cancelled=False),
 
                 condition=Q(cancelled=False),
 
             ),
 
             ),
         ]</pre>
+
         ]</syntaxhighlight>
  
 
</div>
 
</div>
  
 
</div>
 
</div>
In case your model defines a range using two fields, instead of the native
+
如果您的模型使用两个字段而不是本机 PostgreSQL 范围类型定义了一个范围,您应该编写一个使用等效函数的表达式(例如 <code>TsTzRange()</code>),并使用字段的分隔符。 大多数情况下,分隔符将是 <code>'[)'</code>,这意味着下限是包含的,而上限是不包括的。 您可以使用 [[../fields#django.contrib.postgres.fields|RangeBoundary]],它为 [https://www.postgresql.org/docs/current/rangetypes.html#RANGETYPES-INCLUSIVITY 范围边界] 提供表达式映射。 例如:
PostgreSQL range types, you should write an expression that uses the equivalent
 
function (e.g. <code>TsTzRange()</code>), and use the delimiters for the field. Most
 
often, the delimiters will be <code>'[)'</code>, meaning that the lower bound is
 
inclusive and the upper bound is exclusive. You may use the
 
[[../fields#django.contrib.postgres.fields|<code>RangeBoundary</code>]] that provides an
 
expression mapping for the [https://www.postgresql.org/docs/current/rangetypes.html#RANGETYPES-INCLUSIVITY range boundaries]. For example:
 
  
 
<div class="highlight-default notranslate">
 
<div class="highlight-default notranslate">
第156行: 第133行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>from django.contrib.postgres.constraints import ExclusionConstraint
+
<syntaxhighlight lang="python">from django.contrib.postgres.constraints import ExclusionConstraint
 
from django.contrib.postgres.fields import (
 
from django.contrib.postgres.fields import (
 
     DateTimeRangeField,
 
     DateTimeRangeField,
第187行: 第164行:
 
                 condition=Q(cancelled=False),
 
                 condition=Q(cancelled=False),
 
             ),
 
             ),
         ]</pre>
+
         ]</syntaxhighlight>
  
 
</div>
 
</div>
第198行: 第175行:
  
 
</div>
 
</div>
 +
<div class="clearer">
  
[[Category:Django 3.0.x 中文文档]]
+
 
 +
 
 +
</div>
 +
 
 +
[[Category:Django 3.0.x 文档]]

2021年10月31日 (日) 04:09的最新版本

PostgreSQL 特定的数据库约束

PostgreSQL 支持来自 django.contrib.postgres.constraints 模块的额外数据完整性约束。 它们被添加到模型 Meta.constraints 选项中。

ExclusionConstraint

3.0 版中的新功能。


class ExclusionConstraint(*, name, expressions, index_type=None, condition=None)

在数据库中创建排除约束。 在内部,PostgreSQL 使用索引实现排除约束。 默认索引类型为 GiST。 要使用它们,您需要在 PostgreSQL 上激活 btree_gist 扩展 。 您可以使用 BtreeGistExtension 迁移操作安装它。

如果您尝试插入与现有行冲突的新行,则会引发 IntegrityError。 同样,当更新与现有行冲突时。

name

ExclusionConstraint.name

约束的名称。


expressions

ExclusionConstraint.expressions

一个 2 元组的可迭代对象。 第一个元素是表达式或字符串。 第二个元素是表示为字符串的 SQL 运算符。 为避免拼写错误,您可以使用 RangeOperators 将运算符映射到字符串。 例如:

expressions=[
    ('timespan', RangeOperators.ADJACENT_TO),
    (F('room'), RangeOperators.EQUAL),
]

对运营商的限制。

在排除约束中只能使用交换运算符。


index_type

ExclusionConstraint.index_type

约束的索引类型。 可接受的值为 GISTSPGIST。 匹配不区分大小写。 如果未提供,则默认索引类型为 GIST


condition

ExclusionConstraint.condition

一个 Q 对象,它指定将约束限制为行子集的条件。 例如,condition=Q(cancelled=False)

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


例子

以下示例限制同一房间内的重叠预订,不考虑取消的预订:

from django.contrib.postgres.constraints import ExclusionConstraint
from django.contrib.postgres.fields import DateTimeRangeField, RangeOperators
from django.db import models
from django.db.models import Q

class Room(models.Model):
    number = models.IntegerField()


class Reservation(models.Model):
    room = models.ForeignKey('Room', on_delete=models.CASCADE)
    timespan = DateTimeRangeField()
    cancelled = models.BooleanField(default=False)

    class Meta:
        constraints = [
            ExclusionConstraint(
                name='exclude_overlapping_reservations',
                expressions=[
                    ('timespan', RangeOperators.OVERLAPS),
                    ('room', RangeOperators.EQUAL),
                ],
                condition=Q(cancelled=False),
            ),
        ]

如果您的模型使用两个字段而不是本机 PostgreSQL 范围类型定义了一个范围,您应该编写一个使用等效函数的表达式(例如 TsTzRange()),并使用字段的分隔符。 大多数情况下,分隔符将是 '[)',这意味着下限是包含的,而上限是不包括的。 您可以使用 RangeBoundary,它为 范围边界 提供表达式映射。 例如:

from django.contrib.postgres.constraints import ExclusionConstraint
from django.contrib.postgres.fields import (
    DateTimeRangeField,
    RangeBoundary,
    RangeOperators,
)
from django.db import models
from django.db.models import Func, Q


class TsTzRange(Func):
    function = 'TSTZRANGE'
    output_field = DateTimeRangeField()


class Reservation(models.Model):
    room = models.ForeignKey('Room', on_delete=models.CASCADE)
    start = models.DateTimeField()
    end = models.DateTimeField()
    cancelled = models.BooleanField(default=False)

    class Meta:
        constraints = [
            ExclusionConstraint(
                name='exclude_overlapping_reservations',
                expressions=(
                    (TsTzRange('start', 'end', RangeBoundary()), RangeOperators.OVERLAPS),
                    ('room', RangeOperators.EQUAL),
                ),
                condition=Q(cancelled=False),
            ),
        ]