Models
A model describes one table of the database: its columns, its keys, its
relations to other tables, its indexes and its constraints. It is what a
Django model class is: class Train(models.Model), its fields and its
Meta. In rind, a model is a plain Rust struct with #[derive(Model)].
Everything else is built on the models. Queries are written with their columns, migrations are computed from them, and resources serve them over HTTP.
This chapter is long, so it is cut into sections. This first page shows a complete model and what the derive gives you. The next pages take each part of a model in turn, list every option, and show the SQL each one produces.
| Page | What it covers | In Django |
|---|---|---|
| Fields and column types | which Rust type gives which SQL type, NULL, every type rind knows | the field classes: CharField, IntegerField, JSONField… |
| Column options | lengths, defaults, unique columns, indexed columns, generated columns | max_length, default, unique, db_index |
| Types of your own | storing an enum or any type of yours in a column | custom fields, choices |
| Primary keys | id, another key, keys the application gives | primary_key=True, AutoField |
| Foreign keys | pointing to another model, what a deletion does | ForeignKey, on_delete |
| Reverse and many-to-many relations | walking a key backwards, link tables | related_name, ManyToManyField |
| Trees | rows that have a parent among themselves | django-mptt, django-treebeard |
| Indexes and constraints | indexes on several columns, unique together, checks | Meta.indexes, Meta.constraints |
| Scopes and scoped models | named queries on a model; models with no default query | managers, objects.published() |
| Sharing fields | fields written once, used by several models | abstract models, mixins |
| Writing objects | insert, save, update, delete on an object | obj.save(), obj.delete() |
| Behaviours and hooks | what every write of a model does | auto_now, save() overrides, signals |
| Reference | every attribute and every key, in tables |
A first model
Here is the train of the sample application, the railway:
#![allow(unused)]
fn main() {
// sample/crates/fleet/fleet-models/src/lib.rs
use network_models::Station;
use rind::prelude::*;
/// A train: an engine and the wagons it pulls.
#[derive(Debug, Clone, Model)]
#[model(table = "fleet_train")]
#[reverse(name = wagons, model = Wagon, fk = "train_id")]
pub struct Train {
pub id: i64,
#[column(max_length = 10, unique)]
pub number: String,
#[column(max_length = 100)]
pub name: String,
/// `passenger` or `freight`.
#[column(max_length = 10)]
pub kind: String,
/// `active`, `maintenance` or `retired`.
#[column(max_length = 12, default = "'active'", index)]
pub status: String,
/// The station it is kept at.
#[fk(Station, on_delete = restrict, name = depot, reverse = depot_trains)]
pub depot_id: i64,
}
}
Read it from top to bottom:
use rind::prelude::*;brings the derive and the query types (Query,Insert,Db…) into scope. Every models crate starts with it.#[derive(Debug, Clone, Model)]:Modelis the derive that does the work.DebugandCloneare not required, but you will want them.#[model(table = "fleet_train")]names the table. It is required: rind does not make up a name from the crate and the struct.- Each field is a column, and the field’s Rust type gives the column’s
SQL type: an
i64is abigint, aStringwithmax_length = 10is acharacter varying(10). idis the primary key, because it is calledid.#[column(..)]adds what the type cannot say: a length, a default, a unique constraint, an index.depot_idis a foreign key to the stations. The relation is calleddepot.#[reverse(..)]declares the other side of a foreign key that another model holds: the wagons point to their train, so a train haswagons.- The doc comments (
///) are kept. They describe the fields in the OpenAPI document, as Django’shelp_textdoes.
The table this model describes, as rind schema prints it:
CREATE TABLE "fleet_train" (
"id" bigint GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
"number" character varying(10) NOT NULL CONSTRAINT "fleet_train_number_key" UNIQUE,
"name" character varying(100) NOT NULL,
"kind" character varying(10) NOT NULL,
"status" character varying(12) NOT NULL DEFAULT 'active',
"depot_id" bigint NOT NULL
);
CREATE INDEX "fleet_train_status_idx" ON "fleet_train" ("status");
ALTER TABLE "fleet_train" ADD CONSTRAINT "fleet_train_depot_id_fkey" FOREIGN KEY ("depot_id") REFERENCES "network_station" ("id") ON DELETE RESTRICT;
CREATE INDEX "fleet_train_depot_id_idx" ON "fleet_train" ("depot_id");
There is nothing in the table that the struct does not say, and nothing in the struct that the table does not have.
What the derive gives you
With this struct, you can already read trains:
#![allow(unused)]
fn main() {
let active: Vec<Train> = db
.all(&Query::<Train>::new().filter(Train::status().eq("active")))
.await?;
}
The derive gave the struct everything a Django model class has:
- It can be read from a row.
db.all(&query)answers aVec<Train>,db.first(&query)anOption<Train>. - It has a typed path to each column,
Train::number(), and to each relation,Train::depot()andTrain::wagons(). You write queries with them, as you would writeTrain.objects.filter(depot__city="Paris")in Django:Train::depot().city().eq("Paris"). A misspelt name does not compile. - Its schema is known. The migrations compare it with the database and write what changed (Migrations).
- It can write itself:
train.insert(&db),train.save(&db),train.delete(&db)(Writing objects).
The paths are typed. Train::number() is a path to a String, so it can
be compared with a text, and not with a number:
error[E0277]: the trait bound `{integer}: Operand<std::string::String>` is not satisfied
|
| Query::new().filter(Train::number().eq(3))
| -- ^ the trait `Operand<std::string::String>` is not implemented for `{integer}`
Reference lists everything the derive writes.
Coming from Django: there is no automatic
idfield, no automatic table name, and no automatic reverse relation (wagon_set). Everything a model has is written in the struct. This costs a few lines, and it means that what you read is what the database has.
From the struct to the table
A model does not create its table by itself. Three steps, which rind add model prepares for you:
-
The model is listed in the
schema()function of its crate. A model that is not listed has no table, and nothing warns you:#![allow(unused)] fn main() { // sample/crates/fleet/fleet-models/src/lib.rs pub fn schema() -> Vec<rind::schema::Table> { use rind::schema::Table; vec![Table::of::<Train>(), Table::of::<Wagon>(), Table::of::<Driver>()] } pub fn migrations() -> rind::migrations::Domain { rind::migrations::domain!("fleet", schema()) } } -
The domain is in the application:
app()has.models(fleet_models::migrations()). -
A migration is written and applied:
rind make, thenrind migrate(Migrations).
After that, every change to the struct is a new rind make. rind check
fails when the struct and the migrations disagree.
Where models live
A model lives in the models crate of its domain
(crates/fleet/fleet-models): the crate that every other layer of the
domain depends on. Keep this crate free of HTTP: no serializers, no
resources. A model may point to the models of the domains before its
own, never after (Organising an application).
Next: Fields and column types.