Behaviours
Several models of an application often need the same thing: a
created and an updated date, a list of flags, a description in
markdown with its HTML. In Django you write that once, as an abstract
model (the columns and a save() override) and a view mixin (the
filters and the extra routes), and every model and viewset that needs it
inherits from them.
In rind, that shared piece is a behaviour. A behaviour is a type that you list on a model or on a resource, and that adds to it:
- what its writes set (
updatedon every change, the HTML from the markdown); - for a resource, filters of its own (
?flags=fast) and actions of its own (add_flag,get_flags).
Its columns come separately, from a field group that you add to the
model. The feature is behaviours (and markdown for Content).
Coming from Django: a behaviour does what an abstract model and its view mixin did together. It also does what you may have done with a
pre_savesignal: set a column of the row being written.
Why behaviours, and not signals
A Django signal is a function registered somewhere, that runs when a
model is saved. It is easy to add, and hard to follow: when you read the
model, nothing tells you that a signal will change the row, or in which
order the receivers run. A behaviour is listed on the model or the
resource itself, behaviours(Tracking, Content), so you see everything
that a write will do where the model is declared. They run in the order
listed, and the compiler checks that the model has the columns each one
needs.
A behaviour only changes the row being written. What must happen elsewhere when a row is written (other rows, other tables) is a model hook (The model’s hooks) or a resource’s hook (Inputs). Those are also declared on the model or the resource, by name.
A first example
The railway’s lines have the three behaviours that rind gives: when they
were created and changed (Tracking), flags (Flags), and a description
in markdown (Content):
#![allow(unused)]
fn main() {
// sample/crates/network/network-models/src/lib.rs
#[rind::with_fields(
rind::behaviours::tracking,
rind::behaviours::flags,
rind::behaviours::content
)]
#[derive(Debug, Clone, Model)]
// When a line was created and changed, and its description in HTML, are
// the model's: every write sets them, the API's and the code's
// (`line.save(&db)`).
#[model(
table = "network_line",
behaviours(rind::behaviours::Tracking, rind::behaviours::Content)
)]
#[index(name = "network_line_flags_idx", sql = "USING gin (flags)")]
pub struct Line {
pub id: i64,
#[column(max_length = 10, unique)]
pub code: String,
#[column(max_length = 200)]
pub name: String,
// …
}
}
#![allow(unused)]
fn main() {
// sample/crates/network/network-api/src/lines.rs
#[derive(Resource)]
#[resource(
model = Line,
path = "lines",
out = LineOut,
input = LineIn,
delete,
// `Tracking` and `Content` are the model's: they run on every write.
behaviours(Flags, Images<LineImages>, Logo<LineLogo>)
)]
#[rule(superuser)]
#[rule(staff)]
#[rule(anyone, actions(list, retrieve, get_flags, get_image, get_logo))]
pub struct LineResource;
}
There are three parts:
- The columns come from the field groups in
#[rind::with_fields(..)]:trackinggivescreatedandupdated,flagsgivesflags,contentgivescontent_srcandcontent_html(Groups of fields). - The model’s behaviours, in
#[model(behaviours(..))], run on every write of the model, whether it comes from the API or from code (line.save(&db)). - The resource’s behaviours, in
#[resource(behaviours(..))], run on the resource’s writes, and add its filters and actions. A behaviour that needs the request, or adds routes (Flags,Images), can only be the resource’s.
What it does:
POST /lines
{"code": "L1", "name": "Atlantique", "content_src": "From *Paris*"}
{"id": 3, "code": "L1", "name": "Atlantique", "flags": [],
"content_src": "From *Paris*", "content_html": "<p>From <em>Paris</em></p>\n",
"created": "2026-11-27T09:12:03Z", "updated": "2026-11-27T09:12:03Z"}
A later PATCH moves updated and leaves created. A PATCH that
changes content_src writes content_html again; one that does not
change it leaves it.
The compiler checks the columns
A behaviour lists the columns it needs. A resource or a model whose model lacks one does not compile:
error[E0080]: the behaviour `Flags` needs columns the model does not have
Behaviours take types
behaviours(..) takes types, so a behaviour can be generic, configured
by another type: Compiled<Pandoc>, Images<LineImages>.
The behaviours rind gives
Tracking: when an object was created and changed
Tracking sets created and updated to now on a creation, and
updated to now on every change. The columns come from the field group
rind::behaviours::tracking.
Put it on the model, as the railway does, so that writes from code set
the dates too. On the model, a creation always sets both dates, whatever
the object held, as Django’s auto_now_add and auto_now do. The
model’s raw writes (insert_raw, save_raw, update_raw) do not run
it, for an import that keeps its own dates.
On a resource only, Tracking sets created and updated on a
creation unless the write already sets them.
Flags: labels added and removed one by one
Flags are short strings an object carries (night, fast), in a column
flags (a varchar[], from the field group rind::behaviours::flags).
Flags, on a resource, gives it a filter and three actions.
The filter: ?flags=a,b keeps the objects that have every one of
these flags.
GET /lines?flags=fast,night
On a large table, put a GIN index on flags for this filter, as the
railway does: #[index(name = "…_flags_idx", sql = "USING gin (flags)")].
add_flag and remove_flag (POST /lines/{id}/add_flag) take
one flag or several:
POST /lines/3/add_flag
{"flags": ["night", "fast"]}
{"flags": ["night", "fast"]}
add_flagputs the flags sent at the end, only those the object does not have yet, and once each. So the flags keep the order they were added in.remove_flagtakes them out, and leaves the others where they were. Removing a flag the object does not have is not an error.- Both answer with the object’s flags.
- A body with neither
flag(a string) norflags(a list of strings) is a 400. So is a flag that is empty or longer than 30 characters.
get_flags (GET /lines/get_flags) counts how many objects have
each flag, the most frequent first, then by name:
[{"flag": "fast", "count": 12}, {"flag": "night", "count": 3}]
It counts only the objects the request may see (the query of the
request’s mode). The cache keeps its
answer, and add_flag and remove_flag make it stale, since they write
the table.
Coming from Django: this is what a
FlagsAPIViewMixindid in a real Django application, with the same action names and answers. Two things differ: removing a missing flag was a 500 there, andget_flagscounted the whole table, whoever asked.
Compiled and Content: a column computed from another
Compiled<C> writes a column computed from another one, on every write
that sets the source. A write that sets the source to null empties the
target. A write that does not touch the source leaves the target alone.
Content is Compiled with markdown: it renders content_src into
content_html (the field group rind::behaviours::content, the feature
markdown). The railway puts it on the model.
The markdown is rendered with comrak: CommonMark, with GitHub’s tables,
strikethrough, autolinks and footnotes, and typographic quotes, dashes
and ellipses, as pandoc writes them (' becomes ’, -- becomes –).
Raw HTML in the source is not kept, so a <script> in a description is
not sent to browsers. rind::behaviours::Markdown::html(source) renders
a text the same way, for code of your own.
Going further: a rendering of your own
An application that needs another rendering (pandoc itself, shortcuts of
its own) writes its own Compile, and uses Compiled<…> with it:
#![allow(unused)]
fn main() {
use rind::behaviours::{Compile, Compiled};
pub struct Pandoc;
impl Compile for Pandoc {
const SOURCE: &'static str = "content_src";
const TARGET: &'static str = "content_html";
fn compile(source: &str) -> String {
run_pandoc(source) // your own function
}
}
#[resource(…, behaviours(Compiled<Pandoc>))]
}
Compiled<C> works on a model too: #[model(behaviours(Compiled<Pandoc>))].
Images
Image, Dimensions<P>, Images<G> and Logo<L> read an image’s size
on upload, and give a resource a gallery’s and a logo’s actions. They are
described in Images.
In what order they run
On a write through a resource:
- the model’s behaviours, in the order of
#[model(behaviours(..))]; - then the resource’s behaviours, in the order of
#[resource(behaviours(..))]; - then the resource’s own hooks (Inputs).
So a hook sees what the behaviours set. The model’s own writes
(insert, save, update) run only the first step (Writing an
object).
A behaviour works on the write, not on the input. It reads and sets the
columns of the Insert or the Update by their names
(insert.literal("content_src"), insert.sets("created")), so it works
with any input the resource has.
A behaviour’s actions and rules
A behaviour’s actions are the resource’s actions. The resource’s rules
name them like any other action: above, actions(get_flags) lets anyone
count the flags, while only the staff can add them. The rules are checked
when compiling: a rule that names an action the resource does not have
does not compile. The OpenAPI document lists a behaviour’s actions with
the resource’s (OpenAPI).
Writing a behaviour
On a resource
A behaviour of a resource implements Behaviour<R> for every resource
R. Here is one that writes a slug from the name, on a creation:
#![allow(unused)]
fn main() {
use rind::api::{ApiError, Behaviour, Ctx, Resource};
use rind::query::{Insert, Prefix, Value};
pub struct Slugged;
impl<R: Resource> Behaviour<R> for Slugged {
const COLUMNS: &'static [&'static str] = &["name", "slug"];
type Parameters = ();
async fn creating(_ctx: &Ctx, insert: Insert<R::Model>) -> Result<Insert<R::Model>, ApiError> {
let Some(Value::Text(name)) = insert.literal("name") else { return Ok(insert) };
let slug = slugify(name); // your own function
Ok(insert.value(Prefix::root::<R::Model>().col::<String>("slug"), slug))
}
}
}
COLUMNSare the columns the model must have; the compiler checks them.creatingruns before an insert andupdatingbefore an update (it also receives the object as it is). Each has a default that does nothing.type Parametersis what the behaviour reads from the query string:()for nothing, or a struct derivingParameters.filter(query, params)receives it, already read, on a list, and returns the query filtered. The resource lists these parameters with its own, in the OpenAPI document too.FlagsreadsFlagsParams(flags, on a list).actions()gives the behaviour’s actions. A behaviour with actions also names them all inconst ACTIONS(Flagshas&["add_flag", "remove_flag", "get_flags"]). The resource’s rules are checked against these names when compiling (Permissions). A debug build stops, when it makes the routes, on an action the list forgot.
On a model
A behaviour of a model implements rind::query::ModelBehaviour<M>. It
has COLUMNS, inserting(insert) and updating(update). These are not
async and take no request: a model’s behaviour is about the data
only, so that it can run on every write, including those of a job or a
command. A behaviour that needs the request, or adds routes, is a
resource’s. Tracking and Compiled implement both traits, so they can
be put on either.
Reference
| Behaviour | Columns (field group) | On | What it does |
|---|---|---|---|
Tracking | created, updated (tracking) | model, resource | sets both on a creation, updated on a change |
Flags | flags (flags) | resource | the filter ?flags=a,b (objects that have both); the actions add_flag and remove_flag ({"flag": "a"} or {"flags": […]}, answered {"flags": […]}); get_flags, how many of the objects the request may see have each, [{"flag": "a", "count": 12}, …] |
Compiled<C> | C::SOURCE, C::TARGET | model, resource | on a write that sets the source, the target is C::compile(source) |
Content | content_src, content_html (content) | model, resource | Compiled with markdown (feature markdown) |
Image, Dimensions<P>, Images<G>, Logo<L> | an image’s file, width and height; a link table; a foreign key | resource | Images: the size read on upload, a gallery’s and a logo’s actions |
The Behaviour<R> trait
| Item | Default | |
|---|---|---|
const COLUMNS | &[] | the columns the model must have |
const ACTIONS | &[] | the names of its actions |
type Parameters | (required) | what it reads from the query string, () for nothing |
creating(ctx, insert) | returns the insert | before an insert |
updating(ctx, current, update) | returns the update | before an update of current |
filter(query, params) | returns the query | on a list |
actions() | none | its actions |
Markdown checked against pandoc
On the markdown sources of a real Django application, which pandoc
rendered, rind’s HTML is the same for 2,121 of 2,156 producers, 609 of
612 products, 2 of 2 families and 23 of 24 storages. The differences:
quotes whose side is ambiguous (" La Porée "), and a list written
without a blank line before it, which CommonMark reads as a list and
pandoc’s markdown does not.