Skip to main content

ViewSet

Derive Macro ViewSet 

Source
#[derive(ViewSet)]
{
    // Attributes available to this derive:
    #[viewset]
}
Expand description

Derive a router(prefix, pool) -> axum::Router associated method on a marker struct, wiring the full CRUD ViewSet in one annotation.

#[derive(ViewSet)]
#[viewset(
    model        = Post,
    fields       = "id, title, body, author_id",
    filter_fields = "author_id",
    search_fields = "title, body",
    ordering     = "-published_at",
    page_size    = 20,
)]
pub struct PostViewSet;

// Mount into your app:
let app = Router::new()
    .merge(PostViewSet::router("/api/posts", pool.clone()));

Attributes:

  • model = TypeNamerequired. The #[derive(Model)] struct whose SCHEMA constant drives the endpoints.
  • fields = "a, b, c" — scalar fields included in list/retrieve JSON and accepted on create/update (default: all scalar fields).
  • filter_fields = "a, b" — fields filterable via ?a=v query params.
  • search_fields = "a, b" — fields searched by ?search=....
  • ordering = "a, -b" — default list ordering; prefix - for DESC.
  • page_size = N — default page size (default: 20, max: 1000).
  • read_only — flag; wires only list + retrieve (no mutations).
  • permissions(list = "...", retrieve = "...", create = "...", update = "...", destroy = "...") — codenames required per action.