Reverse and many-to-many relations
A foreign key goes from one model to another: a wagon has a train. This
page shows the two other kinds of relations:
- the reverse of a foreign key, which goes the other way: a train has
wagons; - the many-to-many relation, through a link table: a user has
groups, and a group has users.
Why rind asks you to declare the way back
In Django, ForeignKey(Train) on Wagon silently gives every train a
wagon_set (or the related_name). rind gives nothing back unless you
ask. There are two reasons:
- Nothing is implicit. Reading
Train, you see every relation it has. - Crates have an order.
fleet-modelscannot add a function toStation, which lives innetwork-models, unless it does so in a way Rust allows: a trait. The two ways to declare a reverse relation follow from that.
On the target: #[reverse(..)]
When the target model’s crate can name the model that holds the key (both are in the same crate, or the target’s crate depends on the other), declare the relation on the target’s struct:
#![allow(unused)]
fn main() {
// sample/crates/fleet/fleet-models/src/lib.rs
#[derive(Debug, Clone, Model)]
#[model(table = "fleet_train")]
#[reverse(name = wagons, model = Wagon, fk = "train_id")]
pub struct Train { … }
#[derive(Debug, Clone, Model)]
#[model(table = "fleet_wagon")]
pub struct Wagon {
pub id: i64,
#[fk(Train, on_delete = cascade)]
pub train_id: i64,
// …
}
}
| Key | What it is |
|---|---|
name | the relation’s name: Django’s related_name |
model | the model that holds the key |
fk | the column of that model that points here, as a string |
Train::wagons() is now a path, used like any other:
#![allow(unused)]
fn main() {
// the trains with at least 8 wagons
Query::<Train>::new().filter(Train::wagons().count().ge(8))
// the trains that have a sleeper wagon
Query::<Train>::new().filter(Train::wagons().any(|w| w.kind().eq("sleeper")))
}
A reverse relation is a many relation: a train has several wagons. It
is followed with any, count, sum and the other functions of
Filtering through a many relation,
never by a plain .kind(), which would not say which wagon.
The reverse relation adds nothing to the database: it is the same foreign key, walked the other way.
On the key: reverse = …
Often the target cannot name the model that holds the key. A Station
(in network-models) cannot name a Journey (in timetable-models,
which comes after). Then the foreign key gives the relation back itself:
#![allow(unused)]
fn main() {
// sample/crates/timetable/timetable-models/src/lib.rs
pub struct Journey {
// …
#[fk(Station, on_delete = restrict, reverse = departures)]
pub origin_id: i64,
#[fk(Station, on_delete = restrict, reverse = arrivals)]
pub destination_id: i64,
}
}
The derive writes a trait, named <Target><Relation>, here
StationDepartures and StationArrivals, with the function
departures(), and implements it for Station. Code that follows the
relation imports the trait:
#![allow(unused)]
fn main() {
// sample/crates/network/network-api/src/stations/serializers.rs
use timetable_models::StationDepartures as _;
Query::<Station>::new().filter(Station::departures().count().ge(2))
}
as _ imports the trait without giving it a name in the file: only its
functions are needed.
The import is needed even in the crate that declares the key. If you forget it, the compiler tells you which trait to import:
error[E0599]: no associated function or constant named `notes` found for struct `Tag` in the current scope
|
| Query::new().filter(Tag::notes().count().ge(2))
| ^^^^^ associated function or constant not found in `Tag`
|
= help: items from traits can only be used if the trait is in scope
help: trait `TagNotes` which provides `notes` is implemented but not in scope; perhaps you want to import it
|
+ use crate::TagNotes;
The derive also writes <Target>Path<Relation> (StationPathDepartures),
which lets a relation be followed from a path, inside a closure. When you
use it that way, import that trait too.
Which one to use
| Situation | Use |
|---|---|
| both models in the same crate | #[reverse(..)] on the target: no import needed |
| the key’s crate comes after the target’s | reverse = … on the key, and import the trait where it is used |
Two keys to the same model
A journey points twice to the stations. Each key gives its own reverse
relation, with its own name: a station has departures and arrivals.
Two relations with the same name on a model are refused when the code
compiles.
Many-to-many relations
A user belongs to several groups, and a group has several users. The relation goes through a link table, with one row per pair:
#![allow(unused)]
fn main() {
// sample/crates/accounts/accounts-models/src/lib.rs
#[derive(Debug, Clone, Model)]
#[model(table = "accounts_user")]
#[m2m(name = groups, model = Group, through = "accounts_user_groups",
from = "user_id", to = "group_id")]
pub struct User { … }
}
| Key | What it is |
|---|---|
name | the relation’s name |
model | the model at the other end |
through | the name of the link table |
from | the link table’s column that points to this model |
to | the link table’s column that points to the other model |
This is Django’s ManyToManyField. Django names the link table
<app>_<model>_<field>; rind asks you for the name, so that a Django
database is described as it is.
The link table
The link table has no model of its own: the migrations make it from the
declaration. For an Article with tags:
#![allow(unused)]
fn main() {
#[m2m(name = tags, model = Tag, through = "lab_article_tags", from = "article_id", to = "tag_id")]
pub struct Article { … }
}
CREATE TABLE "lab_article_tags" (
"id" bigint GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
"article_id" bigint NOT NULL,
"tag_id" bigint NOT NULL
);
ALTER TABLE "lab_article_tags" ADD CONSTRAINT "lab_article_tags_article_id_tag_id_key" UNIQUE ("article_id", "tag_id");
ALTER TABLE "lab_article_tags" ADD CONSTRAINT "lab_article_tags_article_id_fkey" FOREIGN KEY ("article_id") REFERENCES "lab_article" ("id") ON DELETE CASCADE;
CREATE INDEX "lab_article_tags_article_id_idx" ON "lab_article_tags" ("article_id");
ALTER TABLE "lab_article_tags" ADD CONSTRAINT "lab_article_tags_tag_id_fkey" FOREIGN KEY ("tag_id") REFERENCES "lab_tag" ("id") ON DELETE CASCADE;
CREATE INDEX "lab_article_tags_tag_id_idx" ON "lab_article_tags" ("tag_id");
It is the table Django makes: an id, the two keys, each pair once, and
the links deleted with either end.
When the links carry data of their own (the date a user joined a group,
a role), the link is a model of its own, with two foreign keys: Django’s
through= model. Declare it as a normal model, and its two keys give the
relations.
Following it in queries
#![allow(unused)]
fn main() {
// the articles tagged "rust"
Query::<Article>::new().filter(Article::tags().any(|t| t.name().eq("rust")))
}
Like a reverse relation, a many-to-many relation is followed with any,
count and the other functions of a many relation. The filter is an
EXISTS: an article with two matching tags appears once, without a
.distinct().
The other side
The m2m attribute gives the relation to the model that declares it,
and only to it: User::groups() exists, Group::users() does not.
For the other side, query from the side that has the relation. The users of a group are the users whose groups include it:
#![allow(unused)]
fn main() {
// the users of the group "drivers"
Query::<User>::new().filter(User::groups().any(|g| g.slug().eq("drivers")))
}
Watch out: declaring a second
#[m2m(..)]onGroupwith the same link table,fromandtoswapped, compiles, but the two declarations disagree on the link table’s unique constraint ((user_id, group_id)against(group_id, user_id)), andrind makethen wants to drop and re-create it. Declare a many-to-many relation on one side only.
Adding and removing links
#![allow(unused)]
fn main() {
db.link(&ARTICLE_TAGS, article.id, tag.id).await?; // true: added
db.link(&ARTICLE_TAGS, article.id, tag.id).await?; // false: it was there already
db.unlink(&ARTICLE_TAGS, article.id, tag.id).await?; // true: removed
}
These are Django’s article.tags.add(tag) and .remove(tag).
ARTICLE_TAGS is the relation’s hop: a constant the derive writes for
each relation, named <MODEL>_<RELATION> in capitals. Loaders take it
too, to read the tags of a whole page of articles in one query
(Queries).
In the API, a serializer sends the ids of a many-to-many relation with
#[m2m_ids], and an input writes them.
Next: Trees.