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

Foreign keys

A foreign key is a column that holds the key of a row of another table: a wagon holds the id of its train. It is Django’s ForeignKey. This page shows how to declare one, how it is named, what happens when the row it points to is deleted, and every option.

Declaring a foreign key

#![allow(unused)]
fn main() {
// sample/crates/fleet/fleet-models/src/lib.rs
#[derive(Debug, Clone, Model)]
#[model(table = "fleet_wagon")]
pub struct Wagon {
    pub id: i64,
    #[fk(Train, on_delete = cascade)]
    pub train_id: i64,
    pub position: i32,
    // …
}
}
CREATE TABLE "fleet_wagon" (
    "id" bigint GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
    "train_id" bigint NOT NULL,
    "position" integer NOT NULL,
    …
);

ALTER TABLE "fleet_wagon" ADD CONSTRAINT "fleet_wagon_train_id_fkey" FOREIGN KEY ("train_id") REFERENCES "fleet_train" ("id") ON DELETE CASCADE;
CREATE INDEX "fleet_wagon_train_id_idx" ON "fleet_wagon" ("train_id");

Three things to notice:

  • The field holds the key itself. Its type is the type of the target’s key, i64. There is no “related object” in the struct: what Django calls wagon.train_id is the field, and there is no wagon.train that loads the train when you touch it. (Loading related rows is always explicit in rind, and done for many rows at once: see Queries.)
  • The first argument is the target model, Train. The crate must be able to name it: the target is in the same crate, or in a crate this one depends on.
  • The key gets an index by itself, as in Django.

Nullable keys

A key that may point to nothing is an Option:

#![allow(unused)]
fn main() {
// sample/crates/fleet/fleet-models/src/lib.rs
/// Someone who drives trains. A driver may have an account.
#[fk(User, on_delete = set_null, reverse = drivers)]
pub user_id: Option<i64>,
}

This is Django’s ForeignKey(..., null=True).

The relation and its name

The field is the column; the relation is what queries follow from one model to the other. The relation is named after the field without its _id: the field train_id gives the relation train.

#![allow(unused)]
fn main() {
// the wagons of the trains named "Le Mistral"
Query::<Wagon>::new().filter(Wagon::train().name().eq("Le Mistral"))
}

Wagon::train() is a path to the related train, and .name() a path to its column. This is Django’s Wagon.objects.filter(train__name="Le Mistral"), checked by the compiler. A relation can be followed as far as you like: Wagon::train().depot().city().

To give the relation another name, write name:

#![allow(unused)]
fn main() {
#[fk(Station, on_delete = restrict, name = depot)]
pub depot_id: i64,                  // the relation is `depot`

#[fk(Tag, on_delete = set_null, name = editor)]
pub editor_tag_id: Option<i64>,     // the relation is `editor`, not `editor_tag`
}

A field whose name does not end in _id must have a name:

error: a foreign key field is named `<relation>_id`, or the relation is given: #[fk(Target, name = relation)]
   |
   |     #[fk(Tag)] pub owner: i64
   |                    ^^^^^

What a deletion does: on_delete

When a train is deleted, what becomes of its wagons? on_delete answers, as in Django:

on_deleteWhen the target is deletedSQLDjango
cascadethis row is deleted tooON DELETE CASCADECASCADE
set_nullthis row’s key becomes NULLON DELETE SET NULLSET_NULL
restrictthe deletion is refusedON DELETE RESTRICTPROTECT
(none)the deletion is refused while this row points to it(no clause)DO_NOTHING with a real constraint

Choose by asking what the row is without its target:

  • a wagon without its train means nothing: cascade;
  • a driver can lose their account and stay a driver: set_null;
  • a train cannot lose its depot by accident: restrict. The station must be emptied of its trains first, on purpose.

set_null needs a nullable field (Option<i64>).

Watch out: the derive does not check it yet. #[fk(Tag, on_delete = set_null)] pub tag_id: i64 compiles, and writes ON DELETE SET NULL on a NOT NULL column: the deletion of a tag then fails in the database.

Without on_delete, the constraint has no ON DELETE clause: PostgreSQL refuses to delete a row that is still pointed to, as with restrict (the difference is only when the check runs, which matters with deferred, below).

Who applies the rule. It is the database: the migrations write the rule in the constraint, so it holds for every deletion, through rind or through psql. rind also reads it when the API deletes an object, to say what goes with it (Deleting through the API).

When the key is checked: deferred

#![allow(unused)]
fn main() {
#[fk(Tag, on_delete = restrict, deferred)]
pub reviewer_id: Option<i64>,
// … FOREIGN KEY ("reviewer_id") REFERENCES "lab_tag" ("id") ON DELETE RESTRICT DEFERRABLE INITIALLY DEFERRED;
}

By default PostgreSQL checks a key at each statement. A deferred key is checked when the transaction commits. This allows, inside one transaction, a moment where the key points to a row that does not exist yet: two rows that point to each other, inserted one after the other.

Django creates all its keys deferred. Use deferred to describe a Django database exactly, or when you need the moment above.

No index: unindexed

#![allow(unused)]
fn main() {
#[fk(Tag, unindexed)]
pub other_id: Option<i64>,
// … FOREIGN KEY ("other_id") REFERENCES "lab_tag" ("id");   and no CREATE INDEX
}

Every key gets an index, because a key is almost always filtered on (the wagons of a train), and because deleting the target must find the rows that point to it. Leave it out only for a key that is never searched and whose target is never deleted, on a large table where the index costs.

Rules kept in code: in_code

#![allow(unused)]
fn main() {
#[fk(Tag, on_delete = cascade, in_code)]
pub coded_id: Option<i64>,
// … FOREIGN KEY ("coded_id") REFERENCES "lab_tag" ("id");   no ON DELETE
}

in_code keeps the rule out of the database: the constraint has no ON DELETE clause, but rind’s deletions (the API’s, delete_cascade) still follow on_delete.

This is for a database that Django made. Django never writes its on_delete rules in the database: it applies them in Python, before it deletes. To describe such a database exactly, and to delete as Django would, write the rule with in_code:

#![allow(unused)]
fn main() {
#[fk(GeoCountry, on_delete = set_null, in_code, deferred)]
pub country_id: Option<i64>,
}

The migrations then match the database as it is. In a new database, prefer real rules: they protect the data from every program.

Names of the constraint and the index

The constraint is named <table>_<column>_fkey, and its index <table>_<column>_idx. A database made by another tool has other names; give them so that rind’s migrations and checks match:

#![allow(unused)]
fn main() {
#[fk(Station, on_delete = restrict, constraint = "fleet_train_depot_fk", index = "fleet_train_depot_ix")]
pub depot_id: i64,
}

See Migrations.

One-to-one relations

Django’s OneToOneField is a foreign key whose column is unique. Write exactly that:

#![allow(unused)]
fn main() {
#[derive(Debug, Clone, Model)]
#[model(table = "lab_profile")]
pub struct Profile {
    pub id: i64,
    #[fk(Tag, on_delete = cascade)]
    #[column(unique)]
    pub tag_id: i64,
}
}
"tag_id" bigint NOT NULL CONSTRAINT "lab_profile_tag_id_key" UNIQUE

(The key also gets its usual index, which the unique constraint makes unnecessary.)

A model that points to itself

A key may point to its own model: a region inside a region, an employee and their manager.

#![allow(unused)]
fn main() {
#[fk(Region, on_delete = cascade)]
pub parent_id: Option<i64>,
}

When the key is the parent of a hierarchy, declare it as a tree too, to get the recursive queries.

A model that points twice to the same model

A journey has an origin and a destination, both stations:

#![allow(unused)]
fn main() {
// sample/crates/timetable/timetable-models/src/lib.rs
#[fk(Station, on_delete = restrict, reverse = departures)]
pub origin_id: i64,
#[fk(Station, on_delete = restrict, reverse = arrivals)]
pub destination_id: i64,
}

The relations are origin and destination. On the way back, each key gives the station a relation of its own name, departures and arrivals: see Reverse relations.

A key to a model this crate cannot name

The domains are ordered, and a crate can only use the crates before it. A key that must point up, to a model of a later domain, is written with the name of the table instead of the model:

#![allow(unused)]
fn main() {
// network-models: a station's manager is a user, declared in a later domain
#[fk(table = "accounts_user", on_delete = set_null)]
pub manager_id: Option<i64>,
}

The relation is then declared where both models are known. Organising an application explains it, with the keys key, external and unfollowed.

Summary

KeyWhat it does
Target (first)the model the key points to
name = relationthe relation’s name, when it is not the field without _id
on_delete = cascade | set_null | restrictwhat a deletion of the target does to this row
reverse = relationthe relation the target gets back (Reverse relations)
deferredchecked at commit: DEFERRABLE INITIALLY DEFERRED
unindexedno index
in_codethe rule is applied by rind, not written in the database
constraint = "…", index = "…"the names an existing database gives them
table = "…" (first), key, external, unfolloweda key to a table this crate cannot name (Organising an application)

Next: Reverse and many-to-many relations.