Expand description
DRF-style serializer layer — #[derive(Serializer)] + serializer::ModelSerializer.
Typed JSON output from model instances with field control and validation.
DRF-style serializer layer — typed JSON output from model instances.
A serializer is a Rust struct that maps a Model instance to a
JSON-ready shape, with per-field control over what is included,
renamed, or excluded.
§Quick start
ⓘ
use rustango::Serializer;
use rustango::serializer::ModelSerializer;
#[derive(Serializer, serde::Deserialize, Default)]
#[serializer(model = Post)]
pub struct PostSerializer {
pub id: i64,
pub title: String,
#[serializer(read_only)]
pub created_at: chrono::DateTime<chrono::Utc>,
#[serializer(write_only)]
pub secret: String,
#[serializer(source = "body")]
pub content: String,
#[serializer(skip)]
pub tag_ids: Vec<i64>, // set manually: s.tag_ids = post.tags_m2m().all(&pool).await?
}
// Serialize:
let s = PostSerializer::from_model(&post);
let json = s.to_value();
// Serialize many:
let json_array = PostSerializer::many_to_value(&posts);§Field attributes
| Attribute | Effect on from_model | Effect on JSON output | Effect on writable_fields |
|---|---|---|---|
| (none) | mapped from model | included | yes |
read_only | mapped from model | included | no |
write_only | Default::default() | excluded | yes |
source = "x" | mapped from model.x | included | yes |
skip | Default::default() | included | no |
§Nested serializers
For v0.20.x, nested objects require #[serializer(skip)] — set the field
manually after calling from_model:
ⓘ
let mut s = PostSerializer::from_model(&post);
s.author = AuthorSerializer::from_model(post.author.value().expect("loaded"));Full automatic nested support (#[serializer(nested)] with FK loading) is
planned for a future slice.
§Validation
Add cross-field validation as an inherent method on the serializer struct:
ⓘ
impl PostSerializer {
pub fn validate(&self) -> Result<(), rustango::forms::FormErrors> {
let mut errors = rustango::forms::FormErrors::default();
if self.title.is_empty() {
errors.add("title", "title cannot be empty");
}
if errors.is_empty() { Ok(()) } else { Err(errors) }
}
}Traits§
- Model
Serializer - Core serializer trait. Implemented by
#[derive(Serializer)]structs.