Skip to main content

model_hooks

Attribute Macro model_hooks 

Source
#[model_hooks]
Expand description

Turn an inherent impl block into a ModelHooks implementation.

Helper attributes on the methods (removed from the emitted impl):

  • #[field_validator("a", "b", mode = "after")]: fn(value: &FieldTy) -> Result<(), FieldError>, run on the typed value at the field’s input key; &String coerces to &str. With mode = "before": fn(value: &mut serde_json::Value), run on the raw slot before the field is coerced. Field names are resolved as real fields, so a typo is a compile error. Requires derive(Validate).
  • #[model_validator(mode = "after")]: fn(&self) -> Result<(), FieldError>; mode = "before": fn(input: &mut Value) -> Result<(), FieldError>. Errors are located at the model unless the FieldError has a location.
  • #[computed_field] / #[computed_field(alias = "name")]: fn(&self) -> T with T: Dump + Schema (an explicit type, not impl Trait). Included by Dump (respecting include/exclude) and documented as a readOnly property.
  • #[field_serializer("field")]: fn(value: &FieldTy) -> V, V: Serialize (serde_json::Value included), replaces the field’s dumped value.
  • #[model_serializer]: fn(&self, value: Value) -> Value, applied to the finished object.

Hooks run in declaration order. Generic impls are supported (the generics and where clause are copied); the model then needs #[model_config(hooks)] and the impl’s bounds must be satisfiable where the model is used.