Skip to main content

Module signals

Module signals 

Source
Expand description

Model lifecycle signals: pre_save, post_save, pre_delete, post_delete and m2m_changed (Django django.db.models.signals).

A Signals registry lives on the Db (see Db::with_signals); clones of the handle and the transaction handles derived from it share the same registry. Registration is explicit:

ⓘ
#[receiver(post_save, model = User)]
async fn audit(user: &User, event: &SignalEvent<'_>) -> Result<(), SignalError> {
    // `event.db` is the handle of the operation, so this runs inside the
    // caller's transaction when there is one.
    Ok(())
}

let signals = Signals::new();
signals.connect(audit_receiver());
let db = Db::new(backend).with_signals(signals);

§Semantics

  • Receivers are typed per model and awaited one after the other, in the order they were connected.
  • They receive the same Db as the operation, so inside a transaction they run in it.
  • A failing pre_* receiver aborts the operation (nothing is written) and the error surfaces as OrmError::Signal. Receivers connected after the failing one do not run.
  • A failing post_* receiver returns its error after the statement ran; inside a transaction the caller’s rollback undoes the statement. Use Db::on_commit for work that must only happen after a commit.
  • post_delete fires only when a row was actually removed.
  • Bulk QuerySet update / delete send no signals.
  • m2m_changed fires for add, remove, clear and set (which is a remove of the stale links followed by an add of the missing ones), with the M2mAction Pre* before and Post* after the join-table statements; add and remove with nothing to change send nothing. The receiver is typed on the declaring model and gets the source object, loaded by primary key only when such a receiver is connected.

Structs§

Receiver
One async callback for one signal of one model.
SignalError
Error a receiver returns to fail the operation.
SignalEvent
Context handed to a receiver next to the instance.
Signals
Registry of Receivers. Cheap to clone: clones share one list.

Enums§

M2mAction
The step of a many-to-many mutation an m2m_changed event reports.
SignalKind
What happened, as delivered to a receiver in SignalEvent::kind.
SignalName
The signal a Receiver listens to, without event payload.

Type Aliases§

BoxFuture
Boxed, sendable future returned by receivers.