0

Signals | Django documentation | Django

 2 years ago
source link: https://docs.djangoproject.com/en/dev/ref/signals/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

Model signals

The django.db.models.signals module defines a set of signals sent by the model system.

Warning

Many of these signals are sent by various model methods like __init__() or save() 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, 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().

Model signals sender model can be lazily referenced when connecting a receiver by specifying its full application label. For example, an Question model defined in the polls application could be referenced as 'polls.Question'. This sort of reference can be quite handy when dealing with circular import dependencies and swappable models.

pre_init

django.db.models.signals.pre_init

Whenever you instantiate a Django model, this signal is sent at the beginning of the model’s __init__() method.

Arguments sent with this signal:

sender The model class that just had an instance created. args A list of positional arguments passed to __init__(). kwargs A dictionary of keyword arguments passed to __init__().

For example, the tutorial has this line:

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

The arguments sent to a pre_init handler would be:

Argument Value
sender Question (the class itself)
args [] (an empty list because there were no positional arguments passed to __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

Like pre_init, but this one is sent when the __init__() method finishes.

Arguments sent with this signal:

sender As above: the model class that just had an instance created. instance

The actual instance of the model that’s just been created.

instance._state isn’t set before sending the post_init signal, so _state attributes always have their default values. For example, _state.db is None.

Warning

For performance reasons, you shouldn’t perform queries in receivers of pre_init or post_init signals because they would be executed for each instance returned during queryset iteration.

pre_save

django.db.models.signals.pre_save

This is sent at the beginning of a model’s save() method.

Arguments sent with this signal:

sender The model class. instance The actual instance being saved. 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. update_fields The set of fields to update as passed to Model.save(), or None if update_fields wasn’t passed to save().

post_save

django.db.models.signals.post_save

Like pre_save, but sent at the end of the save() method.

Arguments sent with this signal:

sender The model class. instance The actual instance being saved. created A boolean; True if a new record was created. 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. update_fields The set of fields to update as passed to Model.save(), or None if update_fields wasn’t passed to save().

pre_delete

django.db.models.signals.pre_delete

Sent at the beginning of a model’s delete() method and a queryset’s delete() method.

Arguments sent with this signal:

sender The model class. instance The actual instance being deleted. using The database alias being used. origin
New in Django Development version.

The origin of the deletion being the instance of a Model or QuerySet class.

post_delete

django.db.models.signals.post_delete

Like pre_delete, but sent at the end of a model’s delete() method and a queryset’s delete() method.

Arguments sent with this signal:

sender The model class. instance

The actual instance being deleted.

Note that the object will no longer be in the database, so be very careful what you do with this instance.

using The database alias being used. origin
New in Django Development version.

The origin of the deletion being the instance of a Model or QuerySet class.

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 and post_add actions, this is a set of primary key values that will be, or have been, added to the relation. This may be a subset of the values submitted to be added, since inserts must filter existing values in order to avoid a database IntegrityError.

For the pre_remove and post_remove 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 pk_set, even though they have no effect on the database.

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 connected a handler like this:

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)

and then did something like this:

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

the arguments sent to a m2m_changed handler (toppings_changed in the example above) 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

Sent whenever a model class has been “prepared” – that is, once model has 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 AppConfig.ready() runs after the app registry is fully populated, receivers cannot be connected in that method. One possibility is to connect them AppConfig.__init__() instead, taking care not to import models or trigger calls to the app registry.

Arguments that are sent with this signal:

sender The model class which was just prepared.

Recommend

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK