シグナル

revision-up-to:17812 (1.4) unfinished

ここでは、 Django が送信する組み込みのシグナルについて解説します。

See also

See the documentation on the signal dispatcher for information regarding how to register for and receive signals.

コメントフレームワーク は、 コメントに関するシグナル を送信し ます。

The authentication framework sends signals when a user is logged in / out.

モデル関連のシグナル

django.db.models.signals モジュールでは、モデルシステムから送信され るシグナルを定義しています。

Warning

ここに挙げるシグナルの多くは、 __init__()save() といった、オーバライド可能な様々 なメソッドから送信されます。

従って、これらのメソッドをオーバライドする場合、親クラスのメソッドを呼 び出して、シグナルが送信されるようにせねばなりません。

Note also that Django stores signal handlers as weak references by default, so if your handler is a local function, it may be garbage collected. To prevent this, pass weak=False when you call the signal’s connect().

pre_init

django.db.models.signals.pre_init

Django モデルをインスタンス化するとき、モデルの __init__() 処理の最初の段階で送信されます。

シグナルの引数は以下の通りです:

sender
インスタンスを作成したモデルクラスです。
args
__init__() に渡された固定引数のリスト です。
kwargs
__init__() に渡されたキーワード引数の リストです。

例えば、 チュートリアル には以下のような行があり ます:

p = Poll(question="What's up?", pub_date=datetime.now())

この行の中で送信されるシグナルを pre_init ハンドラで受けたときの引 数は以下の通りです:

引数
sender Poll (クラス自体)
args [] (__init__ には固定引数がないので空)
kwargs {'question': "What's up?", 'pub_date': datetime.now()}

post_init

django.db.models.signals.post_init

pre_init とほぼ同じですが、 __init__() の処理が終る直前に送信されます。

引数は以下の通りです:

sender
pre_init と同じ、インスタンスを生成したモデルクラスです。
instance
実際に生成されたモデルインスタンスです。

pre_save

django.db.models.signals.pre_save

モデルインスタンスの save() の処理の最初に呼 び出されます。

引数は以下の通りです:

sender
モデルクラスです。
instance
これから保存されるインスタンスです。
raw
A boolean; True 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.
リリースノートを参照してください
using
The database alias being used.

post_save

django.db.models.signals.post_save

pre_save に似ていますが、 save() メソッ ドの処理の最後に呼び出されます。

引数は以下の通りです

sender
モデルクラスです。
instance
保存されたインスタンスです。
created
ブール値で、レコードが新たに作成されたときに True を返します。
raw
A boolean; True 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.
リリースノートを参照してください
using
The database alias being used.

pre_delete

django.db.models.signals.pre_delete

モデルインスタンスの delete() メソッド、 およびクエリーセットの delete() メソッド の処理の先頭で呼出されます。

引数は以下の通りです:

sender
モデルクラスです。
instance
削除されるインスタンスです。
リリースノートを参照してください
using
The database alias being used.

post_delete

django.db.models.signals.post_delete

pre_delete に似ていますが、 delete() メソッドおよびクエリーセットの delete() メソッドの処理の最後に呼び出されます。

引数は以下の通りです:

sender
モデルクラスです。
instance

削除されたインスタンスです。

オブジェクトはもはやデータベース上に存在しないので、このインスタン スの扱いには十分注意してください。

リリースノートを参照してください
using
The database alias being used.

m2m_changed

django.db.models.signals.m2m_changed
リリースノートを参照してください

Sent when a ManyToManyField is changed on a model instance. Strictly speaking, this is not a model signal since it is sent by the ManyToManyField, but since it complements the pre_save/post_save and pre_delete/post_delete when it comes to tracking changes to models, it is included here.

Arguments sent with this signal:

sender
The intermediate model class describing the ManyToManyField. This class is automatically created when a many-to-many field is defined; you can access it using the through attribute on the many-to-many field.
instance
The instance whose many-to-many relation is updated. This can be an instance of the sender, or of the class the ManyToManyField is related to.
action

A string indicating the type of update that is done on the relation. This can be one of the following:

"pre_add"
Sent before one or more objects are added to the relation.
"post_add"
Sent after one or more objects are added to the relation.
"pre_remove"
Sent before one or more objects are removed from the relation.
"post_remove"
Sent after one or more objects are removed from the relation.
"pre_clear"
Sent before the relation is cleared.
"post_clear"
Sent after the relation is cleared.
reverse
Indicates which side of the relation is updated (i.e., if it is the forward or reverse relation that is being modified).
model
The class of the objects that are added to, removed from or cleared from the relation.
pk_set

For the pre_add, post_add, pre_remove and post_remove actions, this is a list of primary key values that have been added to or removed from the relation.

For the pre_clear and post_clear actions, this is None.

リリースノートを参照してください
using
The database alias being used.

For example, if a Pizza can have multiple Topping objects, modeled like this:

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

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

If we would do something like this:

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

the arguments sent to a m2m_changed handler would be:

Argument Value
sender Pizza.toppings.through (the intermediate m2m class)
instance p (the Pizza instance being modified)
action "pre_add" (followed by a separate signal with "post_add")
reverse False (Pizza contains the ManyToManyField, so this call modifies the forward relation)
model Topping (the class of the objects added to the Pizza)
pk_set [t.id] (since only Topping t was added to the relation)
using "default" (since the default router sends writes here)

And if we would then do something like this:

>>> t.pizza_set.remove(p)

the arguments sent to a m2m_changed handler would be:

Argument Value
sender Pizza.toppings.through (the intermediate m2m class)
instance t (the Topping instance being modified)
action "pre_remove" (followed by a separate signal with "post_remove")
reverse True (Pizza contains the ManyToManyField, so this call modifies the reverse relation)
model Pizza (the class of the objects removed from the Topping)
pk_set [p.id] (since only Pizza p was removed from the relation)
using "default" (since the default router sends writes here)

class_prepared

django.db.models.signals.class_prepared

モデルクラスの「準備が完了した」ときに呼び出されます。準備の完了とは、モデ ルの定義が読み込まれ、 Django のモデルシステムに組み込まれたことを示します。 Django はこのシグナルを内部的に使っています。通常は、サードパーティ製のアプ リケーションでは使いません。

引数は以下の通りです:

sender
準備の完了したモデルクラスです。

管理コマンド関連のシグナル

django-admin の送信するシグナルです。

post_syncdb

django.db.models.signals.post_syncdb

syncdb コマンドがアプリケーションをインストールした後、または flush コマンドによって送信されます。

このシグナルを待ち受けるハンドラは、 INSTALLED_APPS に登録されて いるいずれかのアプリケーションの management モジュール内に定義せねばな りません。それ以外の場所にハンドラを定義しても、 syncdb がそれらを ロードしないかもしれません。このシグナルのハンドラが行う変更がべき等である (つまりデータベースの変更を伴わない) ことは重要です。 syncdb コマンド の最中に実行されると flush 管理コマンドが失敗するかもしれない からです。

引数は以下の通りです:

sender
インストールされた models モジュールです。つまり、 syncdb"foo.bar.myapp" という名前のアプリケーショ ンをインストールすると、 sender には foo.bar.myapp.models モジュールが入ります。
app
sender と同じです。
created_models
syncdb が生成した全てのモデルクラスからなるリストです。
verbosity

manage.py がどれくらいの情報をスクリーンに表示しているかを示す値で す。詳しくは --verbosity` フラグを参照してください。

post_syncdb を待ち受けている関数は、この引数の値に従って、 スクリーンに表示するメッセージの量を調整してください。

interactive

interactiveTrue の場合、ユーザにコマンドプロンプトを提 示してもかまいません。 interactiveFalse であれば、シグ ナルを待ち受ける関数は、ユーザにプロンプトを表示してはなりません。

たとえば、 django.contrib.auth アプリケーションは、 interactiveTrue の時にしかスーパユーザを作成しません。

For example, yourapp/management/__init__.py could be written like:

from django.db.models.signals import post_syncdb
import yourapp.models

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

post_syncdb.connect(my_callback, sender=yourapp.models)

リクエスト/レスポンス関連のシグナル

コアフレームワークがリクエストを処理する際に送信するシグナルです。

request_started

django.core.signals.request_started

Djang が HTTP リクエストを送信する直前に送信されます。

引数は以下の通りです:

sender
リクエストを処理するハンドラクラス、たとえば django.core.handlers.wsgi.WsgiHandler です。

request_finished

django.core.signals.request_finished

Django が HTTP リクエストの処理を終了した直後に呼び出されます。

引数は以下の通りです:

sender
上と同じく、ハンドラクラスです。

got_request_exception

django.core.signals.got_request_exception

このシグナルは、 Django が HTTP リクエストの処理中に例外に遭遇したときに送 信されます。

引数は以下の通りです:

sender
上と同じく、ハンドラクラスです。
request
HttpRequest オブジェクトです。

テスト関連のシグナル

テストの実行中 にのみ送信されるシグナルです。

setting_changed

リリースノートを参照してください
django.test.signals.setting_changed

This signal is sent when the value of a setting is changed through the django.test.TestCase.setting() context manager or the django.test.utils.override_settings() decorator/context manager.

It’s actually sent twice: when the new value is applied (“setup”) and when the original value is restored (“teardown”).

Arguments sent with this signal:

sender
The settings handler.
setting
The name of the setting.
value
The value of the setting after the change. For settings that initially don’t exist, in the “teardown” phase, value is None.

template_rendered

django.test.signals.template_rendered

テストシステムがテンプレートをレンダするときに送信されます。このシグナルは、 通常の Django サーバの操作では送信されず、テスト中しか使えません。

引数は以下の通りです:

sender
これからレンダされる Template テンプレー トオブジェクトです。
template
sender と同じ値です。
context
テンプレートをレンダするときに渡される Context です。

Database Wrappers

Signals sent by the database wrapper when a database connection is initiated.

connection_created

django.db.backends.signals.connection_created
The connection argument was added

Sent when the database wrapper makes the initial connection to the database. This is particularly useful if you’d like to send any post connection commands to the SQL backend.

Arguments sent with this signal:

sender
The database wrapper class – i.e. django.db.backends.postgresql_psycopg2.DatabaseWrapper or django.db.backends.mysql.DatabaseWrapper, etc.
connection
The database connection that was opened. This can be used in a multiple-database configuration to differentiate connection signals from different databases.