Skip to main content

Module hooks

Module hooks 

Source
Expand description

Model hooks: validators, computed fields and serializers.

#[model_hooks] impl User { ... } implements ModelHooks from #[field_validator], #[model_validator], #[computed_field], #[field_serializer] and #[model_serializer] methods. The Validate/Schema derives call the hooks without an opt-in flag via [Probe] (autoref specialisation): if the model implements ModelHooks the hooks run, otherwise the calls compile to no-ops.

Probing resolves at the call site in generated code, so it only works when the model type is concrete. Generic models (Page<T>) that have hooks must say so with #[model_config(hooks)], which makes the derive call <Self as ModelHooks> directly.

§Execution order (deterministic)

  1. before_model on the raw object (model mode = "before").
  2. For each field in declaration order: before_field, then the field type’s own prepare (coercion, constraints on the raw value).
  3. Deserialization.
  4. Field constraints, then after_fields (field mode = "after" validators, declaration order), then after_model.

Traits§

ModelHooks
Hooks a model can provide. Every method defaults to doing nothing.