Skip to main content

Module serializer

Module serializer 

Source
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

AttributeEffect on from_modelEffect on JSON outputEffect on writable_fields
(none)mapped from modelincludedyes
read_onlymapped from modelincludedno
write_onlyDefault::default()excludedyes
source = "x"mapped from model.xincludedyes
skipDefault::default()includedno

§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§

ModelSerializer
Core serializer trait. Implemented by #[derive(Serializer)] structs.