“Django/docs/3.0.x/ref/signals”的版本间差异

来自菜鸟教程
Django/docs/3.0.x/ref/signals
跳转至:导航、​搜索
(autoload)
 
(Page commit)
 
第1行: 第1行:
 +
{{DISPLAYTITLE:信号 — Django 文档}}
 
<div id="signals" class="section">
 
<div id="signals" class="section">
  
 
= 信号 =
 
= 信号 =
  
A list of all the signals that Django sends. All built-in signals are sent
+
Django 发送的所有信号的列表。 所有内置信号都使用 [[../../topics/signals#django.dispatch.Signal|send()]] 方法发送。
using the [[../../topics/signals#django.dispatch.Signal|<code>send()</code>]] method.
 
  
 
<div class="admonition seealso">
 
<div class="admonition seealso">
  
参见
+
也可以看看
  
See the documentation on the [[../../topics/signals|<span class="doc">signal dispatcher</span>]] for
+
有关如何注册和接收信号的信息,请参阅 [[../../topics/signals|信号调度程序]] 上的文档。
information regarding how to register for and receive signals.
 
  
The [[../../topics/auth/index|<span class="doc">authentication framework</span>]] sends [[../contrib/auth#topics-auth-signals|<span class="std std-ref">signals when
+
[[../../topics/auth/index|认证框架]]在用户登录/注销[[../contrib/auth#topics-auth-signals|时发送]]信号。
a user is logged in / out</span>]].
 
  
  
第21行: 第19行:
  
 
<span id="model-signals"></span>
 
<span id="model-signals"></span>
== Model signals ==
+
== 模型信号 ==
  
The [[#module-django.db.models.signals|<code>django.db.models.signals</code>]] module defines a set of signals sent by the
+
[[#module-django.db.models.signals|django.db.models.signals]] 模块定义了模型系统发送的一组信号。
model system.
 
  
 
<div class="admonition warning">
 
<div class="admonition warning">
第30行: 第27行:
 
警告
 
警告
  
Many of these signals are sent by various model methods like
+
其中许多信号是由各种模型方法发送的,例如 <code>__init__()</code> [[../models/instances#django.db.models.Model|save()]],您可以在自己的代码中覆盖这些方法。
<code>__init__()</code> or [[../models/instances#django.db.models.Model|<code>save()</code>]] that you can
 
override in your own code.
 
  
If you override these methods on your model, you must call the parent class'
+
如果您在模型上覆盖这些方法,则必须调用父类的方法来发送这些信号。
methods for these signals to be sent.
 
  
Note also that Django stores signal handlers as weak references by default,
+
另请注意,Django 默认将信号处理程序存储为弱引用,因此如果您的处理程序是本地函数,则它可能会被垃圾收集。 为了防止这种情况,在调用信号的 [[../../topics/signals#django.dispatch.Signal|connect()]] 时传递 <code>weak=False</code>
so if your handler is a local function, it may be garbage collected. To
 
prevent this, pass <code>weak=False</code> when you call the signal's [[../../topics/signals#django.dispatch.Signal|<code>connect()</code>]].
 
  
  
第45行: 第37行:
 
<div class="admonition note">
 
<div class="admonition note">
  
注解
+
笔记
  
Model signals <code>sender</code> model can be lazily referenced when connecting a
+
模型信号 <code>sender</code> 模型可以在连接接收器时通过指定其完整的应用程序标签来延迟引用。 例如,在 <code>polls</code> 应用程序中定义的 <code>Question</code> 模型可以被引用为 <code>'polls.Question'</code>。 在处理循环导入依赖项和可交换模型时,这种参考非常方便。
receiver by specifying its full application label. For example, an
 
<code>Question</code> model defined in the <code>polls</code> application could be referenced
 
as <code>'polls.Question'</code>. This sort of reference can be quite handy when
 
dealing with circular import dependencies and swappable models.
 
  
  
第57行: 第45行:
 
<div id="pre-init" class="section">
 
<div id="pre-init" class="section">
  
=== <code>pre_init</code> ===
+
=== pre_init ===
  
; <code>django.db.models.signals.</code><code>pre_init</code>
+
; <span class="sig-prename descclassname"><span class="pre">django.db.models.signals.</span></span><span class="sig-name descname"><span class="pre">pre_init</span></span>
 
:  
 
:  
  
Whenever you instantiate a Django model, this signal is sent at the beginning
+
每当您实例化 Django 模型时,该信号都会在模型的 <code>__init__()</code> 方法的开头发送。
of the model's <code>__init__()</code> method.
 
  
Arguments sent with this signal:
+
与此信号一起发送的参数:
  
 
; <code>sender</code>
 
; <code>sender</code>
: The model class that just had an instance created.
+
: 刚刚创建了一个实例的模型类。
 
; <code>args</code>
 
; <code>args</code>
: A list of positional arguments passed to <code>__init__()</code>.
+
: 传递给 <code>__init__()</code> 的位置参数列表。
 
; <code>kwargs</code>
 
; <code>kwargs</code>
: A dictionary of keyword arguments passed to <code>__init__()</code>.
+
: 传递给 <code>__init__()</code> 的关键字参数字典。
  
For example, the [[../../intro/tutorial02|<span class="doc">tutorial</span>]] has this line:
+
例如,[[../../intro/tutorial02|tutorial]] 有这样一行:
  
 
<div class="highlight-default notranslate">
 
<div class="highlight-default notranslate">
第80行: 第67行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>q = Question(question_text=&quot;What's new?&quot;, pub_date=timezone.now())</pre>
+
<syntaxhighlight lang="python">q = Question(question_text="What's new?", pub_date=timezone.now())</syntaxhighlight>
  
 
</div>
 
</div>
  
 
</div>
 
</div>
The arguments sent to a [[#django.db.models.signals.pre_init|<code>pre_init</code>]] handler would be:
+
发送到 [[#django.db.models.signals.pre_init|pre_init]] 处理程序的参数将是:
  
 
{|
 
{|
!width="11%"| Argument
+
!width="11%"| 论据
!width="89%"| Value
+
!width="89%"| 价值
 
|-
 
|-
 
| <code>sender</code>
 
| <code>sender</code>
| <code>Question</code> (the class itself)
+
| <code>Question</code>(类本身)
 
|-
 
|-
 
| <code>args</code>
 
| <code>args</code>
| <code>[]</code> (an empty list because there were no positional
+
| <code>[]</code>(一个空列表,因为没有传递给 <code>__init__()</code> 的位置参数)
arguments passed to <code>__init__()</code>)
 
 
|-
 
|-
 
| <code>kwargs</code>
 
| <code>kwargs</code>
第107行: 第93行:
 
<div id="post-init" class="section">
 
<div id="post-init" class="section">
  
=== <code>post_init</code> ===
+
=== post_init ===
  
; <code>django.db.models.signals.</code><code>post_init</code>
+
; <span class="sig-prename descclassname"><span class="pre">django.db.models.signals.</span></span><span class="sig-name descname"><span class="pre">post_init</span></span>
 
:  
 
:  
  
Like pre_init, but this one is sent when the <code>__init__()</code> method finishes.
+
pre_init 类似,但在 <code>__init__()</code> 方法完成时发送这个。
  
Arguments sent with this signal:
+
与此信号一起发送的参数:
  
 
<dl>
 
<dl>
 
<dt><code>sender</code></dt>
 
<dt><code>sender</code></dt>
<dd><p>As above: the model class that just had an instance created.</p></dd>
+
<dd><p>如上:刚刚创建了一个实例的模型类。</p></dd>
 
<dt><code>instance</code></dt>
 
<dt><code>instance</code></dt>
<dd><p>The actual instance of the model that's just been created.</p>
+
<dd><p>刚刚创建的模型的实际实例。</p>
 
<div class="admonition note">
 
<div class="admonition note">
  
<p>注解</p>
+
<p>笔记</p>
<p>[[../models/instances#django.db.models.Model|<code>instance._state</code>]] isn't set
+
<p>[[../models/instances#django.db.models.Model|instance._state]] 在发送 <code>post_init</code> 信号之前没有设置,所以 <code>_state</code> 属性总是有它们的默认值。 例如,<code>_state.db</code> <code>None</code></p>
before sending the <code>post_init</code> signal, so <code>_state</code> attributes
 
always have their default values. For example, <code>_state.db</code> is
 
<code>None</code>.</p>
 
  
 
</div></dd></dl>
 
</div></dd></dl>
第135行: 第118行:
 
警告
 
警告
  
For performance reasons, you shouldn't perform queries in receivers of
+
出于性能原因,您不应在 <code>pre_init</code> <code>post_init</code> 信号的接收器中执行查询,因为它们将针对查询集迭代期间返回的每个实例执行。
<code>pre_init</code> or <code>post_init</code> signals because they would be executed for
 
each instance returned during queryset iteration.
 
  
  
第145行: 第126行:
 
<div id="pre-save" class="section">
 
<div id="pre-save" class="section">
  
=== <code>pre_save</code> ===
+
=== pre_save ===
  
; <code>django.db.models.signals.</code><code>pre_save</code>
+
; <span class="sig-prename descclassname"><span class="pre">django.db.models.signals.</span></span><span class="sig-name descname"><span class="pre">pre_save</span></span>
 
:  
 
:  
  
This is sent at the beginning of a model's [[../models/instances#django.db.models.Model|<code>save()</code>]]
+
这是在模型的 [[../models/instances#django.db.models.Model|save()]] 方法的开头发送的。
method.
 
  
Arguments sent with this signal:
+
与此信号一起发送的参数:
  
 
; <code>sender</code>
 
; <code>sender</code>
: The model class.
+
: 模型类。
 
; <code>instance</code>
 
; <code>instance</code>
: The actual instance being saved.
+
: 正在保存的实际实例。
 
; <code>raw</code>
 
; <code>raw</code>
: A boolean; <code>True</code> if the model is saved exactly as presented (i.e. when loading a fixture). One should not query/modify other records in the database as the database might not be in a consistent state yet.
+
: 一个布尔值; <code>True</code> 如果模型完全按照显示保存(即 加载夹具时)。 不应查询/修改数据库中的其他记录,因为数据库可能尚未处于一致状态。
 
; <code>using</code>
 
; <code>using</code>
: The database alias being used.
+
: 正在使用的数据库别名。
 
; <code>update_fields</code>
 
; <code>update_fields</code>
: The set of fields to update as passed to [[../models/instances#django.db.models.Model|<code>Model.save()</code>]], or <code>None</code> if <code>update_fields</code> wasn't passed to <code>save()</code>.
+
: 传递给 [[../models/instances#django.db.models.Model|Model.save()]] <code>None</code>(如果 <code>update_fields</code> 未传递给 <code>save()</code>)的字段集。
  
  
第170行: 第150行:
 
<div id="post-save" class="section">
 
<div id="post-save" class="section">
  
=== <code>post_save</code> ===
+
=== post_save ===
  
; <code>django.db.models.signals.</code><code>post_save</code>
+
; <span class="sig-prename descclassname"><span class="pre">django.db.models.signals.</span></span><span class="sig-name descname"><span class="pre">post_save</span></span>
 
:  
 
:  
  
Like [[#django.db.models.signals.pre_save|<code>pre_save</code>]], but sent at the end of the
+
类似于 [[#django.db.models.signals.pre_save|pre_save]],但在 [[../models/instances#django.db.models.Model|save()]] 方法的末尾发送。
[[../models/instances#django.db.models.Model|<code>save()</code>]] method.
 
  
Arguments sent with this signal:
+
与此信号一起发送的参数:
  
 
; <code>sender</code>
 
; <code>sender</code>
: The model class.
+
: 模型类。
 
; <code>instance</code>
 
; <code>instance</code>
: The actual instance being saved.
+
: 正在保存的实际实例。
 
; <code>created</code>
 
; <code>created</code>
: A boolean; <code>True</code> if a new record was created.
+
: 一个布尔值; <code>True</code> 如果创建了新记录。
 
; <code>raw</code>
 
; <code>raw</code>
: A boolean; <code>True</code> if the model is saved exactly as presented (i.e. when loading a fixture). One should not query/modify other records in the database as the database might not be in a consistent state yet.
+
: 一个布尔值; <code>True</code> 如果模型完全按照显示保存(即 加载夹具时)。 不应查询/修改数据库中的其他记录,因为数据库可能尚未处于一致状态。
 
; <code>using</code>
 
; <code>using</code>
: The database alias being used.
+
: 正在使用的数据库别名。
 
; <code>update_fields</code>
 
; <code>update_fields</code>
: The set of fields to update as passed to [[../models/instances#django.db.models.Model|<code>Model.save()</code>]], or <code>None</code> if <code>update_fields</code> wasn't passed to <code>save()</code>.
+
: 传递给 [[../models/instances#django.db.models.Model|Model.save()]] <code>None</code>(如果 <code>update_fields</code> 未传递给 <code>save()</code>)的字段集。
  
  
第197行: 第176行:
 
<div id="pre-delete" class="section">
 
<div id="pre-delete" class="section">
  
=== <code>pre_delete</code> ===
+
=== pre_delete ===
  
; <code>django.db.models.signals.</code><code>pre_delete</code>
+
; <span class="sig-prename descclassname"><span class="pre">django.db.models.signals.</span></span><span class="sig-name descname"><span class="pre">pre_delete</span></span>
 
:  
 
:  
  
Sent at the beginning of a model's [[../models/instances#django.db.models.Model|<code>delete()</code>]]
+
在模型的 [[../models/instances#django.db.models.Model|delete()]] 方法和查询集的 [[../models/querysets#django.db.models.query.QuerySet|delete()]] 方法的开头发送。
method and a queryset's [[../models/querysets#django.db.models.query.QuerySet|<code>delete()</code>]] method.
 
  
Arguments sent with this signal:
+
与此信号一起发送的参数:
  
 
; <code>sender</code>
 
; <code>sender</code>
: The model class.
+
: 模型类。
 
; <code>instance</code>
 
; <code>instance</code>
: The actual instance being deleted.
+
: 被删除的实际实例。
 
; <code>using</code>
 
; <code>using</code>
: The database alias being used.
+
: 正在使用的数据库别名。
  
  
第218行: 第196行:
 
<div id="post-delete" class="section">
 
<div id="post-delete" class="section">
  
=== <code>post_delete</code> ===
+
=== post_delete ===
  
; <code>django.db.models.signals.</code><code>post_delete</code>
+
; <span class="sig-prename descclassname"><span class="pre">django.db.models.signals.</span></span><span class="sig-name descname"><span class="pre">post_delete</span></span>
 
:  
 
:  
  
Like [[#django.db.models.signals.pre_delete|<code>pre_delete</code>]], but sent at the end of a model's
+
类似于 [[#django.db.models.signals.pre_delete|pre_delete]],但在模型的 [[../models/instances#django.db.models.Model|delete()]] 方法和查询集的 [[../models/querysets#django.db.models.query.QuerySet|delete()]] 方法的末尾发送。
[[../models/instances#django.db.models.Model|<code>delete()</code>]] method and a queryset's
 
[[../models/querysets#django.db.models.query.QuerySet|<code>delete()</code>]] method.
 
  
Arguments sent with this signal:
+
与此信号一起发送的参数:
  
 
<dl>
 
<dl>
 
<dt><code>sender</code></dt>
 
<dt><code>sender</code></dt>
<dd><p>The model class.</p></dd>
+
<dd><p>模型类。</p></dd>
 
<dt><code>instance</code></dt>
 
<dt><code>instance</code></dt>
<dd><p>The actual instance being deleted.</p>
+
<dd><p>被删除的实际实例。</p>
<p>Note that the object will no longer be in the database, so be very
+
<p>请注意,该对象将不再存在于数据库中,因此在处理此实例时要非常小心。</p></dd>
careful what you do with this instance.</p></dd>
 
 
<dt><code>using</code></dt>
 
<dt><code>using</code></dt>
<dd><p>The database alias being used.</p></dd></dl>
+
<dd><p>正在使用的数据库别名。</p></dd></dl>
  
  
第243行: 第218行:
 
<div id="m2m-changed" class="section">
 
<div id="m2m-changed" class="section">
  
=== <code>m2m_changed</code> ===
+
=== m2m_changed ===
  
; <code>django.db.models.signals.</code><code>m2m_changed</code>
+
; <span class="sig-prename descclassname"><span class="pre">django.db.models.signals.</span></span><span class="sig-name descname"><span class="pre">m2m_changed</span></span>
 
:  
 
:  
  
Sent when a [[../models/fields#django.db.models|<code>ManyToManyField</code>]] is changed on a model
+
在模型实例上更改 [[../models/fields#django.db.models|ManyToManyField]] 时发送。 严格来说,这不是模型信号,因为它是由 [[../models/fields#django.db.models|ManyToManyField]] 发送的,但因为它补充了 [[#django.db.models.signals.pre_save|pre_save]]/[[#django.db.models.signals.post_save|post_save]] 和 pre_delete[X18] ]/[[#django.db.models.signals.post_delete|post_delete]] 当涉及到跟踪模型的更改时,它包含在这里。
instance. Strictly speaking, this is not a model signal since it is sent by the
 
[[../models/fields#django.db.models|<code>ManyToManyField</code>]], but since it complements the
 
[[#django.db.models.signals.pre_save|<code>pre_save</code>]]/[[#django.db.models.signals.post_save|<code>post_save</code>]] and [[#django.db.models.signals.pre_delete|<code>pre_delete</code>]]/[[#django.db.models.signals.post_delete|<code>post_delete</code>]]
 
when it comes to tracking changes to models, it is included here.
 
  
Arguments sent with this signal:
+
与此信号一起发送的参数:
  
 
<dl>
 
<dl>
 
<dt><code>sender</code></dt>
 
<dt><code>sender</code></dt>
<dd><p>The intermediate model class describing the
+
<dd><p>描述 [[../models/fields#django.db.models|ManyToManyField]] 的中间模型类。 定义多对多字段时会自动创建此类; 您可以使用多对多字段上的 <code>through</code> 属性访问它。</p></dd>
[[../models/fields#django.db.models|<code>ManyToManyField</code>]]. This class is automatically
 
created when a many-to-many field is defined; you can access it using the
 
<code>through</code> attribute on the many-to-many field.</p></dd>
 
 
<dt><code>instance</code></dt>
 
<dt><code>instance</code></dt>
<dd><p>The instance whose many-to-many relation is updated. This can be an
+
<dd><p>多对多关系被更新的实例。 这可以是 <code>sender</code> 的实例,或 [[../models/fields#django.db.models|ManyToManyField]] 相关的类的实例。</p></dd>
instance of the <code>sender</code>, or of the class the
 
[[../models/fields#django.db.models|<code>ManyToManyField</code>]] is related to.</p></dd>
 
 
<dt><code>action</code></dt>
 
<dt><code>action</code></dt>
<dd><p>A string indicating the type of update that is done on the relation.
+
<dd><p>指示对关系进行的更新类型的字符串。 这可以是以下之一:</p>
This can be one of the following:</p>
 
 
<dl>
 
<dl>
 
<dt><code>&quot;pre_add&quot;</code></dt>
 
<dt><code>&quot;pre_add&quot;</code></dt>
<dd><p>Sent ''before'' one or more objects are added to the relation.</p></dd>
+
<dd><p>Sent ''before'' 一个或多个对象被添加到关系中。</p></dd>
 
<dt><code>&quot;post_add&quot;</code></dt>
 
<dt><code>&quot;post_add&quot;</code></dt>
<dd><p>Sent ''after'' one or more objects are added to the relation.</p></dd>
+
<dd><p>''一个或多个对象添加到关系后发送'' </p></dd>
 
<dt><code>&quot;pre_remove&quot;</code></dt>
 
<dt><code>&quot;pre_remove&quot;</code></dt>
<dd><p>Sent ''before'' one or more objects are removed from the relation.</p></dd>
+
<dd><p>Sent ''before'' 一个或多个对象从关系中移除。</p></dd>
 
<dt><code>&quot;post_remove&quot;</code></dt>
 
<dt><code>&quot;post_remove&quot;</code></dt>
<dd><p>Sent ''after'' one or more objects are removed from the relation.</p></dd>
+
<dd><p>''一个或多个对象从关系中移除后发送'' </p></dd>
 
<dt><code>&quot;pre_clear&quot;</code></dt>
 
<dt><code>&quot;pre_clear&quot;</code></dt>
<dd><p>Sent ''before'' the relation is cleared.</p></dd>
+
<dd><p>发送 ''before'' 关系被清除。</p></dd>
 
<dt><code>&quot;post_clear&quot;</code></dt>
 
<dt><code>&quot;post_clear&quot;</code></dt>
<dd><p>Sent ''after'' the relation is cleared.</p></dd></dl>
+
<dd><p>''关系被清除后发送'' </p></dd></dl>
 
</dd>
 
</dd>
 
<dt><code>reverse</code></dt>
 
<dt><code>reverse</code></dt>
<dd><p>Indicates which side of the relation is updated (i.e., if it is the
+
<dd><p>指示更新关系的哪一侧(即,正在修改的是正向关系还是反向关系)。</p></dd>
forward or reverse relation that is being modified).</p></dd>
 
 
<dt><code>model</code></dt>
 
<dt><code>model</code></dt>
<dd><p>The class of the objects that are added to, removed from or cleared
+
<dd><p>添加到关系中、从关系中删除或从关系中清除的对象的类。</p></dd>
from the relation.</p></dd>
 
 
<dt><code>pk_set</code></dt>
 
<dt><code>pk_set</code></dt>
<dd><p>For the <code>pre_add</code> and <code>post_add</code> actions, this is a set of primary key
+
<dd><p>对于 <code>pre_add</code> <code>post_add</code> 操作,这是一组将要或已经添加到关系中的主键值。 这可能是提交要添加的值的子集,因为插入必须过滤现有值以避免数据库 <code>IntegrityError</code></p>
values that will be, or have been, added to the relation. This may be a
+
<p>对于 <code>pre_remove</code> <code>post_remove</code> 操作,这是一组提交以从关系中删除的主键值。 这不取决于这些值是否实际将被删除或已经被删除。 特别是,不存在的值可能会被提交,并且会出现在 <code>pk_set</code> 中,即使它们对数据库没有影响。</p>
subset of the values submitted to be added, since inserts must filter
+
<p>对于 <code>pre_clear</code> <code>post_clear</code> 动作,这是 <code>None</code></p></dd>
existing values in order to avoid a database <code>IntegrityError</code>.</p>
 
<p>For the <code>pre_remove</code> and <code>post_remove</code> actions, this is a set of
 
primary key values that was submitted to be removed from the relation. This
 
is not dependent on whether the values actually will be, or have been,
 
removed. In particular, non-existent values may be submitted, and will
 
appear in <code>pk_set</code>, even though they have no effect on the database.</p>
 
<p>For the <code>pre_clear</code> and <code>post_clear</code> actions, this is <code>None</code>.</p></dd>
 
 
<dt><code>using</code></dt>
 
<dt><code>using</code></dt>
<dd><p>The database alias being used.</p></dd></dl>
+
<dd><p>正在使用的数据库别名。</p></dd></dl>
  
For example, if a <code>Pizza</code> can have multiple <code>Topping</code> objects, modeled
+
例如,如果一个 <code>Pizza</code> 可以有多个 <code>Topping</code> 对象,建模如下:
like this:
 
  
 
<div class="highlight-default notranslate">
 
<div class="highlight-default notranslate">
第310行: 第265行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>class Topping(models.Model):
+
<syntaxhighlight lang="python">class Topping(models.Model):
 
     # ...
 
     # ...
 
     pass
 
     pass
第316行: 第271行:
 
class Pizza(models.Model):
 
class Pizza(models.Model):
 
     # ...
 
     # ...
     toppings = models.ManyToManyField(Topping)</pre>
+
     toppings = models.ManyToManyField(Topping)</syntaxhighlight>
  
 
</div>
 
</div>
  
 
</div>
 
</div>
If we connected a handler like this:
+
如果我们像这样连接一个处理程序:
  
 
<div class="highlight-default notranslate">
 
<div class="highlight-default notranslate">
第327行: 第282行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>from django.db.models.signals import m2m_changed
+
<syntaxhighlight lang="python">from django.db.models.signals import m2m_changed
  
 
def toppings_changed(sender, **kwargs):
 
def toppings_changed(sender, **kwargs):
第333行: 第288行:
 
     pass
 
     pass
  
m2m_changed.connect(toppings_changed, sender=Pizza.toppings.through)</pre>
+
m2m_changed.connect(toppings_changed, sender=Pizza.toppings.through)</syntaxhighlight>
  
 
</div>
 
</div>
  
 
</div>
 
</div>
and then did something like this:
+
然后做了这样的事情:
  
 
<div class="highlight-default notranslate">
 
<div class="highlight-default notranslate">
第344行: 第299行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>&gt;&gt;&gt; p = Pizza.objects.create(...)
+
<syntaxhighlight lang="python">>>> p = Pizza.objects.create(...)
&gt;&gt;&gt; t = Topping.objects.create(...)
+
>>> t = Topping.objects.create(...)
&gt;&gt;&gt; p.toppings.add(t)</pre>
+
>>> p.toppings.add(t)</syntaxhighlight>
  
 
</div>
 
</div>
  
 
</div>
 
</div>
the arguments sent to a [[#django.db.models.signals.m2m_changed|<code>m2m_changed</code>]] handler (<code>toppings_changed</code> in
+
发送到 [[#django.db.models.signals.m2m_changed|m2m_changed]] 处理程序(上例中的 <code>toppings_changed</code>)的参数将是:
the example above) would be:
 
  
 
{|
 
{|
!width="18%"| Argument
+
!width="18%"| 论据
!width="82%"| Value
+
!width="82%"| 价值
 
|-
 
|-
 
| <code>sender</code>
 
| <code>sender</code>
| <code>Pizza.toppings.through</code> (the intermediate m2m class)
+
| <code>Pizza.toppings.through</code>(中级m2m级)
 
|-
 
|-
 
| <code>instance</code>
 
| <code>instance</code>
| <code>p</code> (the <code>Pizza</code> instance being modified)
+
| <code>p</code>(正在修改的 <code>Pizza</code> 实例)
 
|-
 
|-
 
| <code>action</code>
 
| <code>action</code>
| <code>&quot;pre_add&quot;</code> (followed by a separate signal with <code>&quot;post_add&quot;</code>)
+
| <code>&quot;pre_add&quot;</code>(后跟带有 <code>&quot;post_add&quot;</code> 的单独信号)
 
|-
 
|-
 
| <code>reverse</code>
 
| <code>reverse</code>
| <code>False</code> (<code>Pizza</code> contains the
+
| <code>False</code><code>Pizza</code> 包含 [[../models/fields#django.db.models|ManyToManyField]],所以这个调用修改了前向关系)
[[../models/fields#django.db.models|<code>ManyToManyField</code>]], so this call
 
modifies the forward relation)
 
 
|-
 
|-
 
| <code>model</code>
 
| <code>model</code>
| <code>Topping</code> (the class of the objects added to the
+
| <code>Topping</code>(添加到<code>Pizza</code>的对象的类)
<code>Pizza</code>)
 
 
|-
 
|-
 
| <code>pk_set</code>
 
| <code>pk_set</code>
| <code>{t.id}</code> (since only <code>Topping t</code> was added to the relation)
+
| <code>{t.id}</code>(因为只有 <code>Topping t</code> 被添加到关系中)
 
|-
 
|-
 
| <code>using</code>
 
| <code>using</code>
| <code>&quot;default&quot;</code> (since the default router sends writes here)
+
| <code>&quot;default&quot;</code>(因为默认路由器在这里发送写)
 
|}
 
|}
  
And if we would then do something like this:
+
如果我们然后做这样的事情:
  
 
<div class="highlight-default notranslate">
 
<div class="highlight-default notranslate">
第389行: 第340行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>&gt;&gt;&gt; t.pizza_set.remove(p)</pre>
+
<syntaxhighlight lang="python">>>> t.pizza_set.remove(p)</syntaxhighlight>
  
 
</div>
 
</div>
  
 
</div>
 
</div>
the arguments sent to a [[#django.db.models.signals.m2m_changed|<code>m2m_changed</code>]] handler would be:
+
发送到 [[#django.db.models.signals.m2m_changed|m2m_changed]] 处理程序的参数将是:
  
 
{|
 
{|
!width="16%"| Argument
+
!width="16%"| 论据
!width="84%"| Value
+
!width="84%"| 价值
 
|-
 
|-
 
| <code>sender</code>
 
| <code>sender</code>
| <code>Pizza.toppings.through</code> (the intermediate m2m class)
+
| <code>Pizza.toppings.through</code>(中级m2m级)
 
|-
 
|-
 
| <code>instance</code>
 
| <code>instance</code>
| <code>t</code> (the <code>Topping</code> instance being modified)
+
| <code>t</code>(正在修改的 <code>Topping</code> 实例)
 
|-
 
|-
 
| <code>action</code>
 
| <code>action</code>
| <code>&quot;pre_remove&quot;</code> (followed by a separate signal with <code>&quot;post_remove&quot;</code>)
+
| <code>&quot;pre_remove&quot;</code>(后跟带有 <code>&quot;post_remove&quot;</code> 的单独信号)
 
|-
 
|-
 
| <code>reverse</code>
 
| <code>reverse</code>
| <code>True</code> (<code>Pizza</code> contains the
+
| <code>True</code><code>Pizza</code> 包含 [[../models/fields#django.db.models|ManyToManyField]],所以这个调用修改了反向关系)
[[../models/fields#django.db.models|<code>ManyToManyField</code>]], so this call
 
modifies the reverse relation)
 
 
|-
 
|-
 
| <code>model</code>
 
| <code>model</code>
| <code>Pizza</code> (the class of the objects removed from the
+
| <code>Pizza</code>(从<code>Topping</code>中移除的对象的类别)
<code>Topping</code>)
 
 
|-
 
|-
 
| <code>pk_set</code>
 
| <code>pk_set</code>
| <code>{p.id}</code> (since only <code>Pizza p</code> was removed from the
+
| <code>{p.id}</code>(因为只有 <code>Pizza p</code> 从关系中删除)
relation)
 
 
|-
 
|-
 
| <code>using</code>
 
| <code>using</code>
| <code>&quot;default&quot;</code> (since the default router sends writes here)
+
| <code>&quot;default&quot;</code>(因为默认路由器在这里发送写)
 
|}
 
|}
  
第430行: 第377行:
 
<div id="class-prepared" class="section">
 
<div id="class-prepared" class="section">
  
=== <code>class_prepared</code> ===
+
=== class_prepared ===
  
; <code>django.db.models.signals.</code><code>class_prepared</code>
+
; <span class="sig-prename descclassname"><span class="pre">django.db.models.signals.</span></span><span class="sig-name descname"><span class="pre">class_prepared</span></span>
 
:  
 
:  
  
Sent whenever a model class has been &quot;prepared&quot; -- that is, once model has
+
每当模型类已经“准备好”时发送——也就是说,一旦模型被定义并注册到 Django 的模型系统。 Django 在内部使用这个信号; 它通常不用于第三方应用程序。
been defined and registered with Django's model system. Django uses this
 
signal internally; it's not generally used in third-party applications.
 
  
Since this signal is sent during the app registry population process, and
+
由于此信号是在应用注册表填充过程中发送的,并且 [[../applications#django.apps.AppConfig|AppConfig.ready()]] 在应用注册表完全填充后运行,因此无法在该方法中连接接收器。 一种可能性是连接它们 <code>AppConfig.__init__()</code>,注意不要导入模型或触发对应用程序注册表的调用。
[[../applications#django.apps.AppConfig|<code>AppConfig.ready()</code>]] runs after the app
 
registry is fully populated, receivers cannot be connected in that method.
 
One possibility is to connect them <code>AppConfig.__init__()</code> instead, taking
 
care not to import models or trigger calls to the app registry.
 
  
Arguments that are sent with this signal:
+
与此信号一起发送的参数:
  
 
; <code>sender</code>
 
; <code>sender</code>
: The model class which was just prepared.
+
: 刚刚准备好的模型类。
  
  
第456行: 第397行:
 
<div id="management-signals" class="section">
 
<div id="management-signals" class="section">
  
== Management signals ==
+
== 管理信号 ==
  
Signals sent by [[../django-admin|<span class="doc">django-admin</span>]].
+
[[../django-admin|django-admin]] 发送的信号。
  
 
<div id="pre-migrate" class="section">
 
<div id="pre-migrate" class="section">
  
=== <code>pre_migrate</code> ===
+
=== pre_migrate ===
  
; <code>django.db.models.signals.</code><code>pre_migrate</code>
+
; <span class="sig-prename descclassname"><span class="pre">django.db.models.signals.</span></span><span class="sig-name descname"><span class="pre">pre_migrate</span></span>
 
:  
 
:  
  
Sent by the [[../django-admin#django-admin-migrate|<code>migrate</code>]] command before it starts to install an
+
在开始安装应用程序之前由 [[#id1|:djadmin:`migrate`]] 命令发送。 对于缺少 <code>models</code> 模块的应用程序,它不会发出。
application. It's not emitted for applications that lack a <code>models</code> module.
 
  
Arguments sent with this signal:
+
与此信号一起发送的参数:
  
 
<dl>
 
<dl>
 
<dt><code>sender</code></dt>
 
<dt><code>sender</code></dt>
<dd><p>An [[../applications#django.apps|<code>AppConfig</code>]] instance for the application about to
+
<dd><p>即将迁移/同步的应用程序的 [[../applications#django.apps|AppConfig]] 实例。</p></dd>
be migrated/synced.</p></dd>
 
 
<dt><code>app_config</code></dt>
 
<dt><code>app_config</code></dt>
<dd><p>Same as <code>sender</code>.</p></dd>
+
<dd><p><code>sender</code> 相同。</p></dd>
 
<dt><code>verbosity</code></dt>
 
<dt><code>verbosity</code></dt>
<dd><p>Indicates how much information manage.py is printing on screen. See
+
<dd><p>指示 manage.py 在屏幕上打印的信息量。 有关详细信息,请参阅 <code>--verbosity</code> 标志。</p>
the [[../django-admin#cmdoption-verbosity|<code>--verbosity</code>]] flag for details.</p>
+
<p>侦听 [[#django.db.models.signals.pre_migrate|pre_migrate]] 的函数应根据此参数的值调整它们输出到屏幕的内容。</p></dd>
<p>Functions which listen for [[#django.db.models.signals.pre_migrate|<code>pre_migrate</code>]] should adjust what they
 
output to the screen based on the value of this argument.</p></dd>
 
 
<dt><code>interactive</code></dt>
 
<dt><code>interactive</code></dt>
<dd><p>If <code>interactive</code> is <code>True</code>, it's safe to prompt the user to input
+
<dd><p>如果 <code>interactive</code> <code>True</code>,提示用户在命令行输入内容是安全的。 如果 <code>interactive</code> <code>False</code>,则监听此信号的函数不应尝试提示任何内容。</p>
things on the command line. If <code>interactive</code> is <code>False</code>, functions
+
<p>例如,[[../../topics/auth/index#module-django.contrib|django.contrib.auth]] 应用仅在 <code>interactive</code> <code>True</code> 时才提示创建超级用户。</p></dd>
which listen for this signal should not try to prompt for anything.</p>
 
<p>For example, the [[../../topics/auth/index#module-django.contrib|<code>django.contrib.auth</code>]] app only prompts to create a
 
superuser when <code>interactive</code> is <code>True</code>.</p></dd>
 
 
<dt><code>using</code></dt>
 
<dt><code>using</code></dt>
<dd><p>The alias of database on which a command will operate.</p></dd>
+
<dd><p>命令将在其上运行的数据库的别名。</p></dd>
 
<dt><code>plan</code></dt>
 
<dt><code>plan</code></dt>
<dd><p>The migration plan that is going to be used for the migration run. While
+
<dd><p>将用于迁移运行的迁移计划。 虽然该计划不是公共 API,但在极少数情况下需要了解该计划。 计划是一个双元组列表,第一项是迁移类的实例,第二项显示迁移是回滚 (<code>True</code>) 还是应用 (<code>False</code>)</p></dd>
the plan is not public API, this allows for the rare cases when it is
 
necessary to know the plan. A plan is a list of two-tuples with the first
 
item being the instance of a migration class and the second item showing
 
if the migration was rolled back (<code>True</code>) or applied (<code>False</code>).</p></dd>
 
 
<dt><code>apps</code></dt>
 
<dt><code>apps</code></dt>
<dd><p>An instance of [[../applications#module-django|<code>Apps</code>]] containing the state of the
+
<dd><p>[[../applications#module-django|Apps]] 的一个实例,包含迁移运行前的项目状态。 应该使用它而不是全局 [[../applications#django.apps|apps]] 注册表来检索要对其执行操作的模型。</p></dd></dl>
project before the migration run. It should be used instead of the global
 
[[../applications#django.apps|<code>apps</code>]] registry to retrieve the models you
 
want to perform operations on.</p></dd></dl>
 
  
  
第507行: 第434行:
 
<div id="post-migrate" class="section">
 
<div id="post-migrate" class="section">
  
=== <code>post_migrate</code> ===
+
=== post_migrate ===
  
; <code>django.db.models.signals.</code><code>post_migrate</code>
+
; <span class="sig-prename descclassname"><span class="pre">django.db.models.signals.</span></span><span class="sig-name descname"><span class="pre">post_migrate</span></span>
 
:  
 
:  
  
Sent at the end of the [[../django-admin#django-admin-migrate|<code>migrate</code>]] (even if no migrations are run) and
+
[[#id3|:djadmin:`migrate`]](即使没有运行迁移)和 [[#id5|:djadmin:`flush`]] 命令的末尾发送。 对于缺少 <code>models</code> 模块的应用程序,它不会发出。
[[../django-admin#django-admin-flush|<code>flush</code>]] commands. It's not emitted for applications that lack a
 
<code>models</code> module.
 
  
Handlers of this signal must not perform database schema alterations as doing
+
此信号的处理程序不得执行数据库模式更改,因为如果在 [[#id9|:djadmin:`migrate`]] 命令期间运行,这样做可能会导致 [[#id7|:djadmin:`flush`]] 命令失败。
so may cause the [[../django-admin#django-admin-flush|<code>flush</code>]] command to fail if it runs during the
 
[[../django-admin#django-admin-migrate|<code>migrate</code>]] command.
 
  
Arguments sent with this signal:
+
与此信号一起发送的参数:
  
 
<dl>
 
<dl>
 
<dt><code>sender</code></dt>
 
<dt><code>sender</code></dt>
<dd><p>An [[../applications#django.apps|<code>AppConfig</code>]] instance for the application that was
+
<dd><p>刚安装的应用程序的 [[../applications#django.apps|AppConfig]] 实例。</p></dd>
just installed.</p></dd>
 
 
<dt><code>app_config</code></dt>
 
<dt><code>app_config</code></dt>
<dd><p>Same as <code>sender</code>.</p></dd>
+
<dd><p><code>sender</code> 相同。</p></dd>
 
<dt><code>verbosity</code></dt>
 
<dt><code>verbosity</code></dt>
<dd><p>Indicates how much information manage.py is printing on screen. See
+
<dd><p>指示 manage.py 在屏幕上打印的信息量。 有关详细信息,请参阅 <code>--verbosity</code> 标志。</p>
the [[../django-admin#cmdoption-verbosity|<code>--verbosity</code>]] flag for details.</p>
+
<p>侦听 [[#django.db.models.signals.post_migrate|post_migrate]] 的函数应根据此参数的值调整它们输出到屏幕的内容。</p></dd>
<p>Functions which listen for [[#django.db.models.signals.post_migrate|<code>post_migrate</code>]] should adjust what they
 
output to the screen based on the value of this argument.</p></dd>
 
 
<dt><code>interactive</code></dt>
 
<dt><code>interactive</code></dt>
<dd><p>If <code>interactive</code> is <code>True</code>, it's safe to prompt the user to input
+
<dd><p>如果 <code>interactive</code> <code>True</code>,提示用户在命令行输入内容是安全的。 如果 <code>interactive</code> <code>False</code>,则监听此信号的函数不应尝试提示任何内容。</p>
things on the command line. If <code>interactive</code> is <code>False</code>, functions
+
<p>例如,[[../../topics/auth/index#module-django.contrib|django.contrib.auth]] 应用仅在 <code>interactive</code> <code>True</code> 时才提示创建超级用户。</p></dd>
which listen for this signal should not try to prompt for anything.</p>
 
<p>For example, the [[../../topics/auth/index#module-django.contrib|<code>django.contrib.auth</code>]] app only prompts to create a
 
superuser when <code>interactive</code> is <code>True</code>.</p></dd>
 
 
<dt><code>using</code></dt>
 
<dt><code>using</code></dt>
<dd><p>The database alias used for synchronization. Defaults to the <code>default</code>
+
<dd><p>用于同步的数据库别名。 默认为 <code>default</code> 数据库。</p></dd>
database.</p></dd>
 
 
<dt><code>plan</code></dt>
 
<dt><code>plan</code></dt>
<dd><p>The migration plan that was used for the migration run. While the plan is
+
<dd><p>用于迁移运行的迁移计划。 虽然该计划不是公共 API,但在极少数情况下需要了解该计划。 计划是一个双元组列表,第一项是迁移类的实例,第二项显示迁移是回滚 (<code>True</code>) 还是应用 (<code>False</code>)</p></dd>
not public API, this allows for the rare cases when it is necessary to
 
know the plan. A plan is a list of two-tuples with the first item being
 
the instance of a migration class and the second item showing if the
 
migration was rolled back (<code>True</code>) or applied (<code>False</code>).</p></dd>
 
 
<dt><code>apps</code></dt>
 
<dt><code>apps</code></dt>
<dd><p>An instance of [[../applications#django.apps|<code>Apps</code>]] containing the state of the
+
<dd><p>[[../applications#django.apps|Apps]] 的一个实例,包含迁移运行后的项目状态。 应该使用它而不是全局 [[../applications#django.apps|apps]] 注册表来检索要对其执行操作的模型。</p></dd></dl>
project after the migration run. It should be used instead of the global
 
[[../applications#django.apps|<code>apps</code>]] registry to retrieve the models you
 
want to perform operations on.</p></dd></dl>
 
  
For example, you could register a callback in an
+
例如,您可以像这样在 [[../applications#django.apps|AppConfig]] 中注册回调:
[[../applications#django.apps|<code>AppConfig</code>]] like this:
 
  
 
<div class="highlight-default notranslate">
 
<div class="highlight-default notranslate">
第561行: 第469行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>from django.apps import AppConfig
+
<syntaxhighlight lang="python">from django.apps import AppConfig
 
from django.db.models.signals import post_migrate
 
from django.db.models.signals import post_migrate
  
第572行: 第480行:
  
 
     def ready(self):
 
     def ready(self):
         post_migrate.connect(my_callback, sender=self)</pre>
+
         post_migrate.connect(my_callback, sender=self)</syntaxhighlight>
  
 
</div>
 
</div>
第579行: 第487行:
 
<div class="admonition note">
 
<div class="admonition note">
  
注解
+
笔记
  
If you provide an [[../applications#django.apps|<code>AppConfig</code>]] instance as the sender
+
如果您提供 [[../applications#django.apps|AppConfig]] 实例作为发送方参数,请确保信号已在 [[../applications#django.apps.AppConfig|ready()]] 中注册。 <code>AppConfig</code> 是为使用一组修改后的 [[#id11|:setting:`INSTALLED_APPS`]](例如当设置被覆盖时)运行的测试重新创建的,并且应该为每个新的 <code>AppConfig</code> 实例。
argument, please ensure that the signal is registered in
 
[[../applications#django.apps.AppConfig|<code>ready()</code>]]. <code>AppConfig</code>s are recreated for
 
tests that run with a modified set of [[../settings#std-setting-INSTALLED_APPS|<code>INSTALLED_APPS</code>]] (such as
 
when settings are overridden) and such signals should be connected for each
 
new <code>AppConfig</code> instance.
 
  
  
第597行: 第500行:
  
 
<span id="request-response-signals"></span>
 
<span id="request-response-signals"></span>
== Request/response signals ==
+
== 请求/响应信号 ==
  
Signals sent by the core framework when processing a request.
+
处理请求时由核心框架发送的信号。
  
 
<div id="request-started" class="section">
 
<div id="request-started" class="section">
  
=== <code>request_started</code> ===
+
=== request_started ===
  
; <code>django.core.signals.</code><code>request_started</code>
+
; <span class="sig-prename descclassname"><span class="pre">django.core.signals.</span></span><span class="sig-name descname"><span class="pre">request_started</span></span>
 
:  
 
:  
  
Sent when Django begins processing an HTTP request.
+
Django 开始处理 HTTP 请求时发送。
  
Arguments sent with this signal:
+
与此信号一起发送的参数:
  
 
; <code>sender</code>
 
; <code>sender</code>
: The handler class -- e.g. <code>django.core.handlers.wsgi.WsgiHandler</code> -- that handled the request.
+
: 处理程序类——例如 <code>django.core.handlers.wsgi.WsgiHandler</code> – 处理请求。
 
; <code>environ</code>
 
; <code>environ</code>
: The <code>environ</code> dictionary provided to the request.
+
: 提供给请求的 <code>environ</code> 字典。
  
  
第621行: 第524行:
 
<div id="request-finished" class="section">
 
<div id="request-finished" class="section">
  
=== <code>request_finished</code> ===
+
=== request_finished ===
  
; <code>django.core.signals.</code><code>request_finished</code>
+
; <span class="sig-prename descclassname"><span class="pre">django.core.signals.</span></span><span class="sig-name descname"><span class="pre">request_finished</span></span>
 
:  
 
:  
  
Sent when Django finishes delivering an HTTP response to the client.
+
Django 完成向客户端提供 HTTP 响应时发送。
  
Arguments sent with this signal:
+
与此信号一起发送的参数:
  
 
; <code>sender</code>
 
; <code>sender</code>
: The handler class, as above.
+
: 处理程序类,如上。
  
  
第637行: 第540行:
 
<div id="got-request-exception" class="section">
 
<div id="got-request-exception" class="section">
  
=== <code>got_request_exception</code> ===
+
=== got_request_exception ===
  
; <code>django.core.signals.</code><code>got_request_exception</code>
+
; <span class="sig-prename descclassname"><span class="pre">django.core.signals.</span></span><span class="sig-name descname"><span class="pre">got_request_exception</span></span>
 
:  
 
:  
  
This signal is sent whenever Django encounters an exception while processing an incoming HTTP request.
+
每当 Django 在处理传入的 HTTP 请求时遇到异常,就会发送此信号。
  
Arguments sent with this signal:
+
与此信号一起发送的参数:
  
 
; <code>sender</code>
 
; <code>sender</code>
: Unused (always <code>None</code>).
+
: 未使用(总是 <code>None</code>)。
 
; <code>request</code>
 
; <code>request</code>
: The [[../request-response#django.http|<code>HttpRequest</code>]] object.
+
: [[../request-response#django.http|HttpRequest]] 对象。
  
  
第658行: 第561行:
  
 
<span id="test-signals"></span>
 
<span id="test-signals"></span>
== Test signals ==
+
== 测试信号 ==
  
Signals only sent when [[../../topics/testing/overview#running-tests|<span class="std std-ref">running tests</span>]].
+
仅在 [[../../topics/testing/overview#running-tests|运行测试]] 时发送信号。
  
 
<div id="setting-changed" class="section">
 
<div id="setting-changed" class="section">
  
=== <code>setting_changed</code> ===
+
=== setting_changed ===
  
; <code>django.test.signals.</code><code>setting_changed</code>
+
; <span class="sig-prename descclassname"><span class="pre">django.test.signals.</span></span><span class="sig-name descname"><span class="pre">setting_changed</span></span>
 
:  
 
:  
  
This signal is sent when the value of a setting is changed through the
+
当设置的值通过 <code>django.test.TestCase.settings()</code> 上下文管理器或 [[../../topics/testing/tools#django.test|django.test.override_settings()]] 装饰器/上下文管理器更改时发送此信号。
<code>django.test.TestCase.settings()</code> context manager or the
 
[[../../topics/testing/tools#django.test|<code>django.test.override_settings()</code>]] decorator/context manager.
 
  
It's actually sent twice: when the new value is applied (&quot;setup&quot;) and when the
+
它实际上发送了两次:应用新值时(“设置”)和恢复原始值时(“拆卸”)。 使用 <code>enter</code> 参数来区分两者。
original value is restored (&quot;teardown&quot;). Use the <code>enter</code> argument to
 
distinguish between the two.
 
  
You can also import this signal from <code>django.core.signals</code> to avoid importing
+
您也可以从 <code>django.core.signals</code> 导入此信号,以避免在非测试情况下从 <code>django.test</code> 导入。
from <code>django.test</code> in non-test situations.
 
  
Arguments sent with this signal:
+
与此信号一起发送的参数:
  
 
; <code>sender</code>
 
; <code>sender</code>
: The settings handler.
+
: 设置处理程序。
 
; <code>setting</code>
 
; <code>setting</code>
: The name of the setting.
+
: 设置的名称。
 
; <code>value</code>
 
; <code>value</code>
: The value of the setting after the change. For settings that initially don't exist, in the &quot;teardown&quot; phase, <code>value</code> is <code>None</code>.
+
: 更改后的设置值。 对于最初不存在的设置,在“拆解”阶段,<code>value</code> <code>None</code>
 
; <code>enter</code>
 
; <code>enter</code>
: A boolean; <code>True</code> if the setting is applied, <code>False</code> if restored.
+
: 一个布尔值; <code>True</code> 如果设置被应用,<code>False</code> 如果恢复。
  
  
第695行: 第593行:
 
<div id="template-rendered" class="section">
 
<div id="template-rendered" class="section">
  
=== <code>template_rendered</code> ===
+
=== template_rendered ===
  
; <code>django.test.signals.</code><code>template_rendered</code>
+
; <span class="sig-prename descclassname"><span class="pre">django.test.signals.</span></span><span class="sig-name descname"><span class="pre">template_rendered</span></span>
 
:  
 
:  
  
Sent when the test system renders a template. This signal is not emitted during
+
当测试系统呈现模板时发送。 在 Django 服务器的正常运行期间不会发出此信号 - 它仅在测试期间可用。
normal operation of a Django server -- it is only available during testing.
 
  
Arguments sent with this signal:
+
与此信号一起发送的参数:
  
 
; <code>sender</code>
 
; <code>sender</code>
: The [[../templates/api#django.template|<code>Template</code>]] object which was rendered.
+
: 渲染的 [[../templates/api#django.template|Template]] 对象。
 
; <code>template</code>
 
; <code>template</code>
: Same as sender
+
: 与发件人相同
 
; <code>context</code>
 
; <code>context</code>
: The [[../templates/api#django.template|<code>Context</code>]] with which the template was rendered.
+
: 渲染模板所使用的 [[../templates/api#django.template|Context]]
  
  
第719行: 第616行:
  
 
<span id="database-wrappers"></span>
 
<span id="database-wrappers"></span>
== Database Wrappers ==
+
== 数据库包装器 ==
  
Signals sent by the database wrapper when a database connection is
+
启动数据库连接时由数据库包装器发送的信号。
initiated.
 
  
 
<div id="connection-created" class="section">
 
<div id="connection-created" class="section">
  
=== <code>connection_created</code> ===
+
=== connection_created ===
  
; <code>django.db.backends.signals.</code><code>connection_created</code>
+
; <span class="sig-prename descclassname"><span class="pre">django.db.backends.signals.</span></span><span class="sig-name descname"><span class="pre">connection_created</span></span>
 
:  
 
:  
  
Sent when the database wrapper makes the initial connection to the
+
当数据库包装器与数据库建立初始连接时发送。 如果您想将任何后连接命令发送到 SQL 后端,这将特别有用。
database. This is particularly useful if you'd like to send any post
 
connection commands to the SQL backend.
 
  
Arguments sent with this signal:
+
与此信号一起发送的参数:
  
 
; <code>sender</code>
 
; <code>sender</code>
: The database wrapper class -- i.e. <code>django.db.backends.postgresql.DatabaseWrapper</code> or <code>django.db.backends.mysql.DatabaseWrapper</code>, etc.
+
: 数据库包装类——即 <code>django.db.backends.postgresql.DatabaseWrapper</code> <code>django.db.backends.mysql.DatabaseWrapper</code>
 
; <code>connection</code>
 
; <code>connection</code>
: The database connection that was opened. This can be used in a multiple-database configuration to differentiate connection signals from different databases.
+
: 已打开的数据库连接。 这可用于多数据库配置以区分来自不同数据库的连接信号。
  
  
第748行: 第642行:
  
 
</div>
 
</div>
 +
<div class="clearer">
  
[[Category:Django 3.0.x 中文文档]]
+
 
 +
 
 +
</div>
 +
 
 +
[[Category:Django 3.0.x 文档]]

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

信号

Django 发送的所有信号的列表。 所有内置信号都使用 send() 方法发送。

也可以看看

有关如何注册和接收信号的信息,请参阅 信号调度程序 上的文档。

认证框架在用户登录/注销时发送信号。


模型信号

django.db.models.signals 模块定义了模型系统发送的一组信号。

警告

其中许多信号是由各种模型方法发送的,例如 __init__()save(),您可以在自己的代码中覆盖这些方法。

如果您在模型上覆盖这些方法,则必须调用父类的方法来发送这些信号。

另请注意,Django 默认将信号处理程序存储为弱引用,因此如果您的处理程序是本地函数,则它可能会被垃圾收集。 为了防止这种情况,在调用信号的 connect() 时传递 weak=False


笔记

模型信号 sender 模型可以在连接接收器时通过指定其完整的应用程序标签来延迟引用。 例如,在 polls 应用程序中定义的 Question 模型可以被引用为 'polls.Question'。 在处理循环导入依赖项和可交换模型时,这种参考非常方便。


pre_init

django.db.models.signals.pre_init

每当您实例化 Django 模型时,该信号都会在模型的 __init__() 方法的开头发送。

与此信号一起发送的参数:

sender
刚刚创建了一个实例的模型类。
args
传递给 __init__() 的位置参数列表。
kwargs
传递给 __init__() 的关键字参数字典。

例如,tutorial 有这样一行:

q = Question(question_text="What's new?", pub_date=timezone.now())

发送到 pre_init 处理程序的参数将是:

论据 价值
sender Question(类本身)
args [](一个空列表,因为没有传递给 __init__() 的位置参数)
kwargs {'question_text': "What's new?",

'pub_date': datetime.datetime(2012, 2, 26, 13, 0, 0, 775217, tzinfo=<UTC>)}


post_init

django.db.models.signals.post_init

与 pre_init 类似,但在 __init__() 方法完成时发送这个。

与此信号一起发送的参数:

sender

如上:刚刚创建了一个实例的模型类。

instance

刚刚创建的模型的实际实例。

笔记

instance._state 在发送 post_init 信号之前没有设置,所以 _state 属性总是有它们的默认值。 例如,_state.dbNone

警告

出于性能原因,您不应在 pre_initpost_init 信号的接收器中执行查询,因为它们将针对查询集迭代期间返回的每个实例执行。


pre_save

django.db.models.signals.pre_save

这是在模型的 save() 方法的开头发送的。

与此信号一起发送的参数:

sender
模型类。
instance
正在保存的实际实例。
raw
一个布尔值; True 如果模型完全按照显示保存(即 加载夹具时)。 不应查询/修改数据库中的其他记录,因为数据库可能尚未处于一致状态。
using
正在使用的数据库别名。
update_fields
传递给 Model.save()None(如果 update_fields 未传递给 save())的字段集。


post_save

django.db.models.signals.post_save

类似于 pre_save,但在 save() 方法的末尾发送。

与此信号一起发送的参数:

sender
模型类。
instance
正在保存的实际实例。
created
一个布尔值; True 如果创建了新记录。
raw
一个布尔值; True 如果模型完全按照显示保存(即 加载夹具时)。 不应查询/修改数据库中的其他记录,因为数据库可能尚未处于一致状态。
using
正在使用的数据库别名。
update_fields
传递给 Model.save()None(如果 update_fields 未传递给 save())的字段集。


pre_delete

django.db.models.signals.pre_delete

在模型的 delete() 方法和查询集的 delete() 方法的开头发送。

与此信号一起发送的参数:

sender
模型类。
instance
被删除的实际实例。
using
正在使用的数据库别名。


post_delete

django.db.models.signals.post_delete

类似于 pre_delete,但在模型的 delete() 方法和查询集的 delete() 方法的末尾发送。

与此信号一起发送的参数:

sender

模型类。

instance

被删除的实际实例。

请注意,该对象将不再存在于数据库中,因此在处理此实例时要非常小心。

using

正在使用的数据库别名。


m2m_changed

django.db.models.signals.m2m_changed

在模型实例上更改 ManyToManyField 时发送。 严格来说,这不是模型信号,因为它是由 ManyToManyField 发送的,但因为它补充了 pre_save/post_save 和 pre_delete[X18] ]/post_delete 当涉及到跟踪模型的更改时,它包含在这里。

与此信号一起发送的参数:

sender

描述 ManyToManyField 的中间模型类。 定义多对多字段时会自动创建此类; 您可以使用多对多字段上的 through 属性访问它。

instance

多对多关系被更新的实例。 这可以是 sender 的实例,或 ManyToManyField 相关的类的实例。

action

指示对关系进行的更新类型的字符串。 这可以是以下之一:

"pre_add"

Sent before 一个或多个对象被添加到关系中。

"post_add"

一个或多个对象添加到关系后发送

"pre_remove"

Sent before 一个或多个对象从关系中移除。

"post_remove"

一个或多个对象从关系中移除后发送

"pre_clear"

发送 before 关系被清除。

"post_clear"

关系被清除后发送

reverse

指示更新关系的哪一侧(即,正在修改的是正向关系还是反向关系)。

model

添加到关系中、从关系中删除或从关系中清除的对象的类。

pk_set

对于 pre_addpost_add 操作,这是一组将要或已经添加到关系中的主键值。 这可能是提交要添加的值的子集,因为插入必须过滤现有值以避免数据库 IntegrityError

对于 pre_removepost_remove 操作,这是一组提交以从关系中删除的主键值。 这不取决于这些值是否实际将被删除或已经被删除。 特别是,不存在的值可能会被提交,并且会出现在 pk_set 中,即使它们对数据库没有影响。

对于 pre_clearpost_clear 动作,这是 None

using

正在使用的数据库别名。

例如,如果一个 Pizza 可以有多个 Topping 对象,建模如下:

class Topping(models.Model):
    # ...
    pass

class Pizza(models.Model):
    # ...
    toppings = models.ManyToManyField(Topping)

如果我们像这样连接一个处理程序:

from django.db.models.signals import m2m_changed

def toppings_changed(sender, **kwargs):
    # Do something
    pass

m2m_changed.connect(toppings_changed, sender=Pizza.toppings.through)

然后做了这样的事情:

>>> p = Pizza.objects.create(...)
>>> t = Topping.objects.create(...)
>>> p.toppings.add(t)

发送到 m2m_changed 处理程序(上例中的 toppings_changed)的参数将是:

论据 价值
sender Pizza.toppings.through(中级m2m级)
instance p(正在修改的 Pizza 实例)
action "pre_add"(后跟带有 "post_add" 的单独信号)
reverse FalsePizza 包含 ManyToManyField,所以这个调用修改了前向关系)
model Topping(添加到Pizza的对象的类)
pk_set {t.id}(因为只有 Topping t 被添加到关系中)
using "default"(因为默认路由器在这里发送写)

如果我们然后做这样的事情:

>>> t.pizza_set.remove(p)

发送到 m2m_changed 处理程序的参数将是:

论据 价值
sender Pizza.toppings.through(中级m2m级)
instance t(正在修改的 Topping 实例)
action "pre_remove"(后跟带有 "post_remove" 的单独信号)
reverse TruePizza 包含 ManyToManyField,所以这个调用修改了反向关系)
model Pizza(从Topping中移除的对象的类别)
pk_set {p.id}(因为只有 Pizza p 从关系中删除)
using "default"(因为默认路由器在这里发送写)


class_prepared

django.db.models.signals.class_prepared

每当模型类已经“准备好”时发送——也就是说,一旦模型被定义并注册到 Django 的模型系统。 Django 在内部使用这个信号; 它通常不用于第三方应用程序。

由于此信号是在应用注册表填充过程中发送的,并且 AppConfig.ready() 在应用注册表完全填充后运行,因此无法在该方法中连接接收器。 一种可能性是连接它们 AppConfig.__init__(),注意不要导入模型或触发对应用程序注册表的调用。

与此信号一起发送的参数:

sender
刚刚准备好的模型类。


管理信号

django-admin 发送的信号。

pre_migrate

django.db.models.signals.pre_migrate

在开始安装应用程序之前由 :djadmin:`migrate` 命令发送。 对于缺少 models 模块的应用程序,它不会发出。

与此信号一起发送的参数:

sender

即将迁移/同步的应用程序的 AppConfig 实例。

app_config

sender 相同。

verbosity

指示 manage.py 在屏幕上打印的信息量。 有关详细信息,请参阅 --verbosity 标志。

侦听 pre_migrate 的函数应根据此参数的值调整它们输出到屏幕的内容。

interactive

如果 interactiveTrue,提示用户在命令行输入内容是安全的。 如果 interactiveFalse,则监听此信号的函数不应尝试提示任何内容。

例如,django.contrib.auth 应用仅在 interactiveTrue 时才提示创建超级用户。

using

命令将在其上运行的数据库的别名。

plan

将用于迁移运行的迁移计划。 虽然该计划不是公共 API,但在极少数情况下需要了解该计划。 计划是一个双元组列表,第一项是迁移类的实例,第二项显示迁移是回滚 (True) 还是应用 (False)。

apps

Apps 的一个实例,包含迁移运行前的项目状态。 应该使用它而不是全局 apps 注册表来检索要对其执行操作的模型。


post_migrate

django.db.models.signals.post_migrate

:djadmin:`migrate`(即使没有运行迁移)和 :djadmin:`flush` 命令的末尾发送。 对于缺少 models 模块的应用程序,它不会发出。

此信号的处理程序不得执行数据库模式更改,因为如果在 :djadmin:`migrate` 命令期间运行,这样做可能会导致 :djadmin:`flush` 命令失败。

与此信号一起发送的参数:

sender

刚安装的应用程序的 AppConfig 实例。

app_config

sender 相同。

verbosity

指示 manage.py 在屏幕上打印的信息量。 有关详细信息,请参阅 --verbosity 标志。

侦听 post_migrate 的函数应根据此参数的值调整它们输出到屏幕的内容。

interactive

如果 interactiveTrue,提示用户在命令行输入内容是安全的。 如果 interactiveFalse,则监听此信号的函数不应尝试提示任何内容。

例如,django.contrib.auth 应用仅在 interactiveTrue 时才提示创建超级用户。

using

用于同步的数据库别名。 默认为 default 数据库。

plan

用于迁移运行的迁移计划。 虽然该计划不是公共 API,但在极少数情况下需要了解该计划。 计划是一个双元组列表,第一项是迁移类的实例,第二项显示迁移是回滚 (True) 还是应用 (False)。

apps

Apps 的一个实例,包含迁移运行后的项目状态。 应该使用它而不是全局 apps 注册表来检索要对其执行操作的模型。

例如,您可以像这样在 AppConfig 中注册回调:

from django.apps import AppConfig
from django.db.models.signals import post_migrate

def my_callback(sender, **kwargs):
    # Your specific logic here
    pass

class MyAppConfig(AppConfig):
    ...

    def ready(self):
        post_migrate.connect(my_callback, sender=self)

笔记

如果您提供 AppConfig 实例作为发送方参数,请确保信号已在 ready() 中注册。 AppConfig 是为使用一组修改后的 :setting:`INSTALLED_APPS`(例如当设置被覆盖时)运行的测试重新创建的,并且应该为每个新的 AppConfig 实例。


请求/响应信号

处理请求时由核心框架发送的信号。

request_started

django.core.signals.request_started

当 Django 开始处理 HTTP 请求时发送。

与此信号一起发送的参数:

sender
处理程序类——例如 django.core.handlers.wsgi.WsgiHandler – 处理请求。
environ
提供给请求的 environ 字典。


request_finished

django.core.signals.request_finished

当 Django 完成向客户端提供 HTTP 响应时发送。

与此信号一起发送的参数:

sender
处理程序类,如上。


got_request_exception

django.core.signals.got_request_exception

每当 Django 在处理传入的 HTTP 请求时遇到异常,就会发送此信号。

与此信号一起发送的参数:

sender
未使用(总是 None)。
request
HttpRequest 对象。


测试信号

仅在 运行测试 时发送信号。

setting_changed

django.test.signals.setting_changed

当设置的值通过 django.test.TestCase.settings() 上下文管理器或 django.test.override_settings() 装饰器/上下文管理器更改时发送此信号。

它实际上发送了两次:应用新值时(“设置”)和恢复原始值时(“拆卸”)。 使用 enter 参数来区分两者。

您也可以从 django.core.signals 导入此信号,以避免在非测试情况下从 django.test 导入。

与此信号一起发送的参数:

sender
设置处理程序。
setting
设置的名称。
value
更改后的设置值。 对于最初不存在的设置,在“拆解”阶段,valueNone
enter
一个布尔值; True 如果设置被应用,False 如果恢复。


template_rendered

django.test.signals.template_rendered

当测试系统呈现模板时发送。 在 Django 服务器的正常运行期间不会发出此信号 - 它仅在测试期间可用。

与此信号一起发送的参数:

sender
渲染的 Template 对象。
template
与发件人相同
context
渲染模板所使用的 Context


数据库包装器

启动数据库连接时由数据库包装器发送的信号。

connection_created

django.db.backends.signals.connection_created

当数据库包装器与数据库建立初始连接时发送。 如果您想将任何后连接命令发送到 SQL 后端,这将特别有用。

与此信号一起发送的参数:

sender
数据库包装类——即 django.db.backends.postgresql.DatabaseWrapperdjango.db.backends.mysql.DatabaseWrapper
connection
已打开的数据库连接。 这可用于多数据库配置以区分来自不同数据库的连接信号。