Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Serializers: what an answer contains

A serializer says what an object looks like in an answer: which keys the JSON has, and where each value comes from. It is the read side of Django REST framework’s ModelSerializer.

In DRF, one ModelSerializer usually does two jobs: it turns an object into JSON, and it reads and validates the JSON a client sends. rind splits these two jobs into two structs:

  • the serializer (this chapter) says what goes out;
  • the input (Inputs) says what can be written.

They are separate because they are rarely the same. An answer has nested objects, counts, values the application computes, and ids sent under the name of their relation. A write has none of these: it has the columns a client may change, with their checks (a maximum length, a list of choices, a key that must exist). With one class, DRF needs read_only, write_only and read_only_fields to tell the two apart. With two structs, each one only has what it needs, and a field that is not in the input cannot be written, whatever the serializer sends.

A first serializer

This is part of the serializer of the sample’s stations:

#![allow(unused)]
fn main() {
// sample/crates/network/network-api/src/stations/serializers.rs
use chrono::NaiveDate;
use network_models::Station;
use rind::Serializer;

#[derive(Debug, Clone, Serializer)]
#[serializer(model = Station)]
pub struct StationOut {
    #[field(mandatory)]
    pub id: Option<i64>,
    #[field(mandatory)]
    pub code: Option<String>,
    #[field(mandatory)]
    pub name: Option<String>,
    pub city: Option<String>,
    #[field(mandatory)]
    pub status: Option<String>,
    pub platforms: Option<i32>,
    pub services: Option<Vec<String>>,
    pub opened: Option<Option<NaiveDate>>,
    #[field(name = "region")]
    pub region_id: Option<i64>,
    #[field(name = "manager")]
    pub manager_id: Option<Option<i64>>,
    // …
}
}

#[serializer(model = Station)] says which model the serializer reads, like DRF’s Meta.model. A field without an attribute is the model’s column of the same name. The resource names the serializer with out = StationOut (Resources).

The derive writes the JSON itself: do not also derive serde::Serialize.

A request for one station gets:

GET /stations/3
{"id": 3, "code": "BRE", "name": "Brest", "city": "Brest", "status": "open",
 "platforms": 6, "services": ["wifi"], "opened": null, "region": 3,
 "manager": null, "photo": null, "position": null}

Why every field is an Option

Every field of a serializer is an Option. The client chooses which fields it wants (see below), and None means “this field was not asked for”. A field that was not asked for is not read from the database, and its key is not in the JSON. It is not sent as null: it is absent.

A column that can be NULL therefore has two Options: Option<Option<NaiveDate>>. The outer one says whether the field was selected; the inner one is the value, None for NULL. A selected NULL goes out as null, as "opened": null above.

The derive checks this: a field that is not an Option does not compile.

The name of a field in the JSON

The key in the JSON is the name of the Rust field, unless the field says another one with name = "…". A raw identifier loses its r#: pub r#type: Option<String> goes out as "type".

A foreign key is the common case. The model’s field is region_id, and DRF sends it under the relation’s name, region. rind does the same only when you say so:

#![allow(unused)]
fn main() {
#[field(name = "region")]
pub region_id: Option<i64>,
}

Without name, the key is region_id.

Note: rind add resource writes a serializer with one field per column of the model, under the column’s name. A foreign key such as author_id therefore goes out as "author_id". Add #[field(name = "author")] to send it as DRF does, and give the input’s field the same name (#[input(name = "author", fk = Author)], see Inputs) so that a client reads and writes the same key.

A field can also read a column of another name, with column = …:

#![allow(unused)]
fn main() {
// crates/rind/tests/derive.rs
#[field(name = "editor", column = edited_by)]
pub editor_id: Option<Option<i64>>,
}

Choosing which fields are sent

By default, an answer has every field except those marked on_request. The client can change this with three query parameters:

ParameterWhat is sent
fields=a,bonly a, b, and the mandatory fields
omit=a,beverything that would be sent, except a and b, even if they are mandatory
include=a,bthe default fields, and also a and b (usually on_request fields)

This is what the DynamicFieldsMixin of many DRF projects does. Two keys of a field control it:

  • mandatory: the field is always sent, even when fields does not name it. Only omit removes it. The id is usually mandatory.
  • on_request: the field is not sent by default. A client must ask for it with fields or include. Use it for costly fields: nested objects, counts, computed values.

For example, with id, code, name and status mandatory:

GET /stations?fields=city&page_size=1
{"parameters": {…}, "nav": {…},
 "results": [{"id": 3, "code": "BRE", "name": "Brest", "city": "Brest", "status": "open"}]}
GET /stations?fields=city&omit=name,status,code&page_size=1
{"parameters": {…}, "nav": {…}, "results": [{"id": 3, "city": "Brest"}]}

A few rules apply at the edges:

  • A name that is not a field is a 400: {"detail": "Unknown field(s): nope."}. A resource declared with ignore_unknown_fields ignores such names instead.
  • An empty fields= selects no field, except the mandatory ones.
  • When fields is given, include is not read, except for its nested selections.
  • A field the user may not read is never sent, even when it is asked for (see Who may read a field and a mode’s hide(..) in Permissions).
  • The same parameters apply to the answer of a write: a POST or a PATCH with ?fields=… gets those fields back.

A list reads only the columns its fields need. GET /stations?fields=city reads the columns of city and of the mandatory fields, not the whole row.

A field that brings others: implies

Sometimes a field only makes sense with another one: a client that asks for a book’s tags also needs its title, say. implies(..) selects the other fields too, one level deep:

#![allow(unused)]
fn main() {
// crates/rind/tests/derive.rs
#[nested(many, m2m = BOOK_TAGS, on_request, implies(title))]
pub tags_details: Option<Vec<TagOut>>,
}

A field sent by default when a parameter is there

A distance to a point only exists when the request gives the point. default_with = "near", together with on_request, sends the field by default when the request has a non-empty near parameter, and keeps it on request otherwise:

#![allow(unused)]
fn main() {
#[computed(loader = near_km, key = id, optional, on_request, default_with = "near")]
pub near_km: Option<i64>,
}

fields and omit still decide: ?near=…&fields=id,name does not send near_km. With optional on the #[computed] field and a loader that gives no value without near, the key is not there either. The parameter is read at every level, so this also works for a field of a nested serializer.

Leaving a null out

A selected field whose value is NULL goes out as null. Sometimes you want the key to be absent instead. DRF does that when a dotted source goes through a null key (source="manager.username" on a station without a manager), and some serializers drop every null. skip_null does the same for one field:

#![allow(unused)]
fn main() {
/// The manager's user name; absent for a station without a manager.
#[annotated(expr = Station::manager().username(), skip_null, on_request)]
pub manager_name: Option<Option<String>>,
}
GET /stations?fields=id,manager_name&omit=code,name,status&ordering=id
{"parameters": {…}, "nav": {…},
 "results": [{"id": 1, "manager_name": "sam"}, {"id": 2, "manager_name": "sam"}, {"id": 3}, …]}

#[serializer(.., skip_nulls)] puts skip_null on every field that can be null. The OpenAPI document then says that the field is never null, and may be absent.

Objects inside an object

A nested field sends a related object, or a list of them, inside the answer. It is DRF’s nested serializer (region = RegionSerializer()). There are three kinds:

#![allow(unused)]
fn main() {
/// One object, behind a foreign key.
#[nested(key = region_id, fields(id, name), on_request)]
pub region_details: Option<RegionOut>,

/// Behind a foreign key that can be null.
#[nested(key = passenger_id, on_request)]
pub passenger_details: Option<Option<PassengerOut>>,

/// A list: the rows that point to this one.
#[nested(many, by = Wagon::train_id(), fields(id, position, kind, capacity), on_request)]
pub wagons_details: Option<Vec<WagonOut>>,
}
  • key = region_id names the model’s foreign key. The type is the nested serializer. For a nullable key, write Option<Option<S>> so that a missing target goes out as null.
  • many, by = Wagon::train_id() sends the rows whose train_id is this row’s id. The type is Option<Vec<S>>.
  • many, m2m = HOP sends the targets of a many-to-many relation (HOP is the constant that the model’s #[m2m(..)] makes).
  • fields(..) fixes which fields of the nested serializer are sent there. Without it, the nested serializer sends its own default fields.

The nested serializer must derive Clone, since several rows of a page can point to the same object.

GET /stations?fields=region_details&page_size=2
{"parameters": {…}, "nav": {…},
 "results": [{"id": 3, "code": "BRE", "name": "Brest", "status": "open",
              "region_details": {"id": 3, "name": "Finistère"}},
             {"id": 6, "code": "MIL", "name": "Milano Centrale", "status": "open",
              "region_details": {"id": 5, "name": "Italia"}}]}

Nested objects are read for the whole page. rind runs one query per nested field, whatever the number of rows, never one per row. This is what you would write by hand in DRF with select_related and prefetch_related; here there is nothing to forget.

Coming from Django: a serializer can use a serializer of another domain. The trains send their depot with StationBrief, which the network domain shares in its network-shared crate (Organising an application).

Choosing fields inside a nested field

The same three parameters choose the fields inside a nested field, with the same rules:

ParameterWhat is sent
fields=id,region_details[parent]region_details, with parent and its mandatory fields
fields=region_details.parentthe same, in a short form; it can be repeated
include=region_details[parent]what the field sends by default, and parent (read even when fields is given)
omit=region_details[name]what the field sends, without name; omit=region_details removes the whole field

Selections go as deep as the nested fields do, up to five levels. A name given several times is merged: wagons_details.kind,wagons_details.capacity is wagons_details[kind,capacity]. When a request says nothing about a nested field, it sends what the derive fixes with fields(..).

A nested field only opens what it says. Inside a nested field, a request can ask for the fields that the derive sends there (its fields(..), or the child’s default fields) and the fields named in allow(..). Any other name is unknown there, and is a 400. Without allow, a request can narrow what the field sends, never widen it:

#![allow(unused)]
fn main() {
#[nested(key = region_id, fields(id, name), allow(parent), on_request)]
pub region_details: Option<RegionOut>,
}
GET /stations?fields=region_details.parent&page_size=2
{"parameters": {…}, "nav": {…},
 "results": [{"id": 3, "code": "BRE", "name": "Brest", "status": "open",
              "region_details": {"id": 3, "name": "Finistère", "parent": 2}},
             {"id": 6, "code": "MIL", "name": "Milano Centrale", "status": "open",
              "region_details": {"id": 5, "name": "Italia", "parent": null}}]}

allow(*) opens every field of the child serializer, the on_request ones included.

Filtering a nested list

A many nested field can take filters, an ordering and a search. The derive names them:

#![allow(unused)]
fn main() {
#[nested(
    many,
    by = Wagon::train_id(),
    fields(id, position, kind, capacity),
    filters = WagonFilters,      // a FilterSet of the nested model
    ordering = wagon_ordering,   // fn() -> Ordering
    search = wagon_search,       // fn() -> Vec<SearchField>
    on_request
)]
pub wagons_details: Option<Vec<WagonOut>>,
}

The client gives them in parentheses, right after the field’s name:

GET /trains?fields=wagons_details(kind=freight)
GET /trains?fields=wagons_details(positions=1,2;ordering=-capacity)[kind,capacity]
GET /trains?fields=wagons_details(search=sleep).kind
GET /trains?fields=wagons_details(kind=freight)[kind]&omit=number
{"parameters": {…}, "nav": {…},
 "results": [{"id": 2, "wagons_details": [{"id": 4, "kind": "freight"}, {"id": 5, "kind": "freight"}]},
             {"id": 3, "wagons_details": []},
             {"id": 1, "wagons_details": []}]}
  • Filters are separated by ;, because a value can be a comma-separated list. A value cannot hold ; or ).
  • The filters come before the selection: wagons_details(kind=freight)[id].
  • They narrow the rows of the field (a query = .. of the derive still applies), for the whole page, in the same single query. A client’s ordering replaces the derive’s.
  • These are 400 errors that name the field: an unknown filter, a wrong value, the same filter given two values, and parentheses on a field that takes none (a foreign key’s target, a value). For example: {"detail": "Unknown filter(s) for `wagons_details`: colour."}.
  • The filterset is usually the one of the nested model’s own resource. The ordering and the search can be that resource’s too (Labels::ordering, Labels::search).

A real Django application often sends values under made-up names, such as cdata_12 for “the data with key 12”. With rind, this becomes a filter: cdata_details(keys=12,14).

The ids of a many-to-many relation

For a many-to-many field, DRF sends the list of the related ids by default. #[m2m_ids(..)] does the same:

#![allow(unused)]
fn main() {
// sample/crates/network/network-api/src/lines.rs
/// The images of its gallery, added and removed by the actions of `Images`.
#[m2m_ids(hop = network_models::LINE_IMAGES, link_order)]
pub images: Option<Vec<i64>>,
}

hop is the relation’s constant, <MODEL>_<RELATION>, made by the model’s #[m2m(..)] (Models). The ids are read in one query per page. They are ordered by the related key or, with link_order, by the link table’s id, which is the order in which the links were made.

DRF reads instance.images.all(), so the ids come in the target model’s Meta.ordering. rind does not know such an ordering, so you say it with query = .., a query on the target. The ids are read through it, in its order, and only those it keeps are sent (still one query per page, with the link table joined to the target):

#![allow(unused)]
fn main() {
#[m2m_ids(
    hop = network_models::LINE_IMAGES,
    query = Query::<Image>::new().order_by([Image::title().asc()]),
    on_request
)]
pub images_by_title: Option<Vec<i64>>,
}

query and link_order say two different orders, so they cannot be used together.

Values the database computes

#[annotated(expr = …)] adds an SQL expression to the list’s query. It is DRF’s queryset.annotate(..) with a field that reads the annotation:

#![allow(unused)]
fn main() {
#[annotated(expr = Station::departures().count(), on_request)]
pub departures_count: Option<i64>,

#[annotated(
    expr = Train::wagons().filter(|w| w.kind().ne("freight")).sum(|w| w.capacity()),
    on_request
)]
pub seats: Option<Option<i64>>,
}
GET /trains?fields=wagons_count,seats&omit=number&ordering=id
{"parameters": {…}, "nav": {…},
 "results": [{"id": 1, "wagons_count": 3, "seats": 8},
             {"id": 2, "wagons_count": 2, "seats": null},
             {"id": 3, "wagons_count": 1, "seats": 50}]}

The expression is only computed when the field is asked for. It can be any expression of the query layer, and the same expression can order the list. It can use ctx, the request (its user, its parameters), and it can be an Option: when it is None for a request, the field is left out.

Values the application computes

Some values are easier to compute in Rust than in SQL. A loader is an async function that receives the keys of the whole page and gives back a value for each key. It is called once per page, and usually runs one query:

#![allow(unused)]
fn main() {
#[computed(loader = region_path, key = region_id, on_request)]
pub region_path: Option<Vec<String>>,

/// The names of each region's ancestors and its own, from the root.
async fn region_path(ctx: &Ctx, ids: Vec<i64>) -> Result<HashMap<i64, Vec<String>>, ApiError> {
    let up = Region::ancestors_of(ids);
    …
}
}

key names the model’s field whose values are given to the loader. A key that the loader gives no value for gets the type’s default value (an empty list here). With optional, the field is left out for that row instead.

This replaces DRF’s SerializerMethodField, which runs once per object and so often makes one query per row.

A loader that reads typed parameters says so on the serializer: #[serializer(model = Station, parameters(StationFilters))].

Names that stand for fields

A column that a client shows is not always a field. A list may show region_name, which the client reads from region_details. The serializer can say which names bring which fields:

#![allow(unused)]
fn main() {
#[derive(Debug, Clone, Serializer)]
#[serializer(
    model = Station,
    alias(departures = (departures_count, planned_departures)),
    prefix(region_ = region_details),
)]
pub struct StationOut { … }
}
RequestWhat it brings
fields=departuresdepartures_count and planned_departures
fields=region_name,region_coderegion_details, once
fields=regionthe field region: a field’s own name is the field
omit=departuresremoves the two counts
  • An alias is one name. A prefix matches every longer name that starts with it and that is not a field or an alias. Every matching prefix applies.
  • What they bring is read as if the request had named it: it must be a field the user may read and, inside a nested field, one the field lets the request reach. Its own implies(..) apply.
  • They take no selection and no filters: departures[id] is a 400. Give the selection to the field itself.
  • A nested serializer’s aliases work inside its field.
  • The derive checks that each target is a field, and that an alias is not a field’s name. A field that brings others says so with implies(..).
  • The OpenAPI document lists them in the fields parameter.

Types of your own

A type of your application used in a serializer must say its JSON schema, for the OpenAPI document. Implement rind::api::openapi::JsonSchema for it; without it, the code does not compile.

Reference

Kinds of fields

AttributeThe valueDRF
none, or #[field(..)]the model’s column of the same name, or column = …a model field
#[nested(key = fk, ..)]the target of a foreign key, through a serializera nested serializer
#[nested(many, by = Child::fk(), ..)]the rows that point to this onemany=True on a reverse relation
#[nested(many, m2m = HOP, ..)]the targets of a many-to-many relationmany=True on an m2m
#[m2m_ids(hop = HOP, ..)]the ids of a many-to-many relationPrimaryKeyRelatedField(many=True)
#[annotated(expr = …, ..)]an SQL expression, computed by the databaseannotate()
#[computed(loader = f, key = k, ..)]a value computed by a function, for the whole pageSerializerMethodField

Keys every kind takes

KeyMeaning
name = "…"the key in the JSON; by default the Rust field’s name (without r#)
description = "…"the OpenAPI description, instead of the doc comment; "" gives none
mandatoryalways sent, unless omit names it
on_requestsent only when fields or include names it
default_with = "param"with on_request: sent by default when the request has param, not empty
skip_nulla null value is left out, as if not selected; only on a field that can be null (Option<Option<T>> or Option<serde_json::Value>)
implies(a, b)selecting this field also selects a and b (one level)
readable(..)who may read the field: staff, superuser, authenticated, group = "…", with = function (Permissions)

Keys of each kind

KindKeys
#[field]column = other (the model’s field); with = function (turns the model’s value into the output’s: a date format, a unit)
#[nested]key = fk (a foreign key) and optionally via(Model, field) (through one intermediate model); or many with by = Child::fk() or m2m = HOP; from = field (the row’s own key, when it is not id); query = … (the rows of a many relation, when not all of them; required when the related model is scoped); fields(..); allow(..) or allow(*); for many only: filters = F, ordering = f, search = f
#[m2m_ids]hop = HOP (required); key = field (the row’s own key, when it is not id); link_order or query = …
#[annotated]expr = … (required); from = field (the row’s own key, when it is not id); with = function (the value is read as the type the function takes, then turned into the field’s)
#[computed]loader = f and key = field (required); optional

The loader of a #[computed] field is async fn(ctx: &Ctx, keys: Vec<i64>) -> Result<HashMap<i64, V>, E>.

The target of a foreign key (#[nested(key = ..)]) is read whatever the target model’s scope, and it takes no query, filters, ordering or search: a target that a filter left out could not be told apart from no target.

#[serializer(..)] on the struct

KeyMeaning
model = Mthe model (required)
alias(name = field, other = (a, b))names that stand for fields
prefix(name_ = field)every longer name starting with name_ that is not a field or an alias
skip_nullsskip_null on every field that can be null
parameters(P, ..)the typed parameters its loaders read

The doc comment of the struct becomes its description in the OpenAPI document, and each field’s doc comment becomes the field’s.

The selection syntax

list    := item ("," item)*
item    := name ("(" filters ")")? ("." item | "[" list "]")?
filters := filter (";" filter)*
filter  := name "=" value

A selection goes at most five levels deep, and one parameter holds at most 200 names, all levels together. Filters in omit are a 400: they mean nothing there.

Nulls and joins

A dotted value read through a join, such as Station::manager().username(), is null both when the key is null and when the value itself is null. On a nullable column, skip_null leaves out both. DRF sends null for the second case.