Loading related rows
A model holds its columns, never its related rows: a Journey has a
train_id, not a train. To show a page of journeys with their trains,
you read the trains too. The wrong way is one query per journey (the
"N+1" problem); the right way is one query for the trains of the whole
page. This is Django's prefetch_related, and rind's loaders do it.
#![allow(unused)] fn main() { // sample/tests/db.rs let journeys = db.all(&Query::<Journey>::new()).await?; let trains: HashMap<i64, Train> = db .load_one(Query::<Train>::new(), journeys.iter().map(|j| j.train_id)) .await?; for journey in &journeys { let train = &trains[&journey.train_id]; println!("{} by {}", journey.code, train.name); } }
Two queries in all, whatever the number of journeys. A loader answers a
HashMap keyed by the key you gave.
Serializers do this by themselves for their nested fields: you need loaders in your own code (an operation, an action, a job).
The target of a foreign key: load_one
#![allow(unused)] fn main() { let trains = db.load_one(Query::<Train>::new(), [1, 2, 2]).await?; // {1: Train { name: "Atlantique", … }, 2: Train { name: "Armor Fret", … }} }
load_one(query, keys) reads the rows of query whose primary key
is one of keys, and answers them by key. Give it the foreign keys of a
page; repeated keys are read once.
The rows that point here: load_many
#![allow(unused)] fn main() { let by_train: HashMap<i64, Vec<Wagon>> = db .load_many( Query::<Wagon>::new().order_by([Wagon::position().asc()]), Wagon::train_id(), [1, 2, 99, 2], ) .await?; // {1: [wagons 1, 2, 3], 2: [wagons 4, 5]} }
load_many(query, key, keys) reads the rows of query whose column
key is one of keys, and groups them by that column. It is the reverse
of a foreign key: the wagons of some trains.
Through a link table: load_m2m
#![allow(unused)] fn main() { let groups: HashMap<i64, Vec<Group>> = db .load_m2m(Query::<Group>::new().order_by([Group::slug().asc()]), &USER_GROUPS, [3, 4, 5]) .await?; // {3: ["shippers"], 4: ["drivers", "shippers"]} }
load_m2m(query, &hop, keys) reads the rows of query linked to each of
keys through a many-to-many relation. USER_GROUPS is the relation's
hop, a constant the model derive writes for each relation, named
<MODEL>_<RELATION> in capitals: the relation groups of User.
The hop must lead to the query's model: load_m2m(Query::<Station>::new(), &USER_GROUPS, …) is refused before any query.
Only the keys: load_m2m_ids and load_m2m_ids_in
When you need the ids at the other end, not the rows:
#![allow(unused)] fn main() { // The link table alone; `true`: in the order the links were made. let ids: HashMap<i64, Vec<i64>> = db.load_m2m_ids(&USER_GROUPS, [3, 4, 5], true).await?; // {3: [2], 4: [1, 2], 5: []} // Through a query on the target, in its order (and only the targets it keeps). let ids = db .load_m2m_ids_in(Query::<Group>::new().order_by([Group::slug().desc()]), &USER_GROUPS, [4]) .await?; // {4: [2, 1]}: shippers, then drivers }
load_m2m_ids reads only the link table: it is the cheapest. With
false, the ids are in the order of the target's key. Note that it
answers an empty list for a key without links (5: []), where the other
loaders leave such a key out of the map.
What all loaders do
- The query's filters and order are kept.
load_many(Query::<Wagon>::new().filter(Wagon::kind().eq("freight")), …)reads only the freight wagons; the order of each list is the query's. - Keys are sorted and made unique before they are sent.
- A key with no related row is not in the map, except for
load_m2m_idsandload_m2m_ids_in, which give it an empty list: what a serializer sends for an m2m field without links. Use.get(&key)and handleNone, or.get(&key).map(Vec::as_slice).unwrap_or_default()for the lists. - An empty list of keys sends nothing at all: no query, no connection.
- Very long lists are cut into queries of 10,000 keys each.
Summary
| Loader | Reads | Keyed by | Django |
|---|---|---|---|
load_one(query, keys) | the rows with these primary keys | the primary key | select_related, or prefetch_related of a key |
load_many(query, key, keys) | the rows whose key column is in keys | key | prefetch_related("wagons") |
load_m2m(query, &hop, keys) | the rows linked to keys | the origin's key | prefetch_related("groups") |
load_m2m_ids(&hop, keys, link_order) | the linked ids, from the link table | the origin's key | values_list on the through table |
load_m2m_ids_in(query, &hop, keys) | the linked ids, through a query on the target | the origin's key |
Next: Writing rows.