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

Sharing fields

Several models often have the same fields: created and updated on every table, an image with its width and height, the columns a user model needs to sign in. In Django you write them once in an abstract model or a mixin, and inherit from it:

class Tracked(models.Model):
    created = models.DateTimeField(auto_now_add=True)
    updated = models.DateTimeField(auto_now=True)

    class Meta:
        abstract = True

class Shelf(Tracked):
    name = models.CharField(max_length=100)

Rust structs have no inheritance. rind has field groups instead: fields written once, and pasted into each struct that asks for them, before the derives read the struct.

Defining a group

#![allow(unused)]
fn main() {
rind::field_group! {
    tracked {
        #[column(default = "now()")]
        pub created: DateTime<Utc>,
        #[column(default = "now()")]
        pub updated: DateTime<Utc>,
    }
}
}

field_group! takes a name, tracked, and a list of fields written exactly as in a struct, with their attributes and doc comments.

Using it

#![allow(unused)]
fn main() {
#[rind::with_fields(tracked)]
#[derive(Debug, Clone, Model)]
#[model(table = "shelf")]
pub struct Shelf {
    pub id: i64,
    #[column(max_length = 100)]
    pub name: String,
}
}

#[rind::with_fields(tracked)] adds the group’s fields at the end of the struct. For the derive, and for the rest of your code, Shelf simply has four fields: id, name, created and updated. It has the columns, the paths (Shelf::created()), and the migrations create them.

Write with_fields above the derives. Attributes run from top to bottom: the fields must be in the struct before #[derive(Model)] reads it. Below the derive, the fields would arrive too late, and the derive would not see them.

Several groups can be included at once: #[rind::with_fields(tracked, flags)].

Groups across crates

A group is visible in its own crate. Written pub, it can be used from other crates, by its path:

#![allow(unused)]
fn main() {
// in a crate `common-models`
rind::field_group! {
    pub tracked { … }
}

// in another crate
#[rind::with_fields(common_models::tracked)]
#[derive(Debug, Clone, Model)]
pub struct Shelf { … }
}

(A group is a macro behind the scenes, so it can also be imported with use common_models::tracked; and named alone.)

Groups that rind gives

GroupFieldsFor
rind::behaviours::trackingcreated, updated (timestamp with time zone, default now())the Tracking behaviour
rind::behaviours::flagsflags (character varying(30)[], default '{}')the Flags behaviour
rind::behaviours::contentcontent_src, content_html (text, default '')the Content behaviour (markdown)
rind::images::imageimage (a File), image_width, image_heightImages
rind_auth::user_basepassword, last_login, is_activeSigning in: Django’s AbstractBaseUser

The sample’s user model, for example:

#![allow(unused)]
fn main() {
// sample/crates/accounts/accounts-models/src/lib.rs
#[rind::with_fields(rind_auth::user_base)]
#[derive(Debug, Clone, Model)]
#[model(table = "accounts_user")]
pub struct User {
    pub id: i64,
    pub username: String,
    // … and `password`, `last_login`, `is_active` from the group
}
}

A behaviour checks, when the application compiles, that the model has the columns it needs. Including its group is the easy way to have them.

Not only for models

A field group is a list of fields, and any struct can include it. The same mechanism works for filtersets, serializers and inputs: the filters every list of located objects has, the output fields that go with tracked.

A group can leave a name open, given by each struct that includes it. This is how a group of filters can name the paths of a model it does not know:

#![allow(unused)]
fn main() {
rind::field_group! {
    location_filters {
        #[filter(path = Root::location().city())]
        pub city: Option<String>,
    }
}

#[rind::with_fields(location_filters(Root = Storage))]
#[derive(Debug, Default, FilterSet)]
#[filterset(model = Storage)]
pub struct StorageFilters {
    #[filter(path = Storage::status())]
    pub status: Option<String>,
}
}

Root = Storage replaces Root by Storage in the group’s fields.

What a group cannot do

  • It adds fields only: not attributes of the struct (#[model(..)], #[index(..)], #[reverse(..)]). Write those on each model.
  • It cannot add methods. Write a trait, or functions, for shared code.
  • Two groups, or a group and the struct, cannot define the same field.

Coming from Django: there is no table for the group and no inheritance between models: Shelf is not a Tracked. Django’s multi-table inheritance (a child table with a one-to-one key to its parent) has no equivalent; write the two models and the one-to-one key yourself.

Next: Writing objects.