Rustango docs

Relations: foreign keys, M2M, generic

Declare and traverse relationships between models.

Foreign keys

Declare a many-to-one relation with #[rustango(fk = "...", on = "id")]. The column stores the referenced id; eager-load the related row with select_related.

#[derive(Model)]
#[rustango(table = "comment")]
pub struct Comment {
    #[rustango(primary_key)] pub id: Auto<i64>,
    #[rustango(fk = "post", on = "id")] pub post_id: i64,
    pub body: String,
}

let c = Comment::objects().select_related("post").first(&pool).await?;

Many-to-many

M2M relations use a through-table; load the far side with prefetch_related, which batches a single IN (…) query and stitches results in memory — no N+1.

Generic foreign keys

The ContentType framework lets one column point at rows in any table (comments-on-anything, audit logs). ContentType::for_model::<T>() resolves the app-label + model-name registry.

Avoid N+1

Always reach for select_related (joins) or prefetch_related (batched) when you render a relation in a loop.