Filters, search, ordering, pages
A list endpoint rarely sends every row in one block. The client narrows
it (?status=open), searches it (?search=rennes), sorts it
(?ordering=-platforms) and reads it one page at a time (?page=2).
In Django REST framework, these four jobs belong to four tools:
django-filter’s FilterSet, DRF’s SearchFilter, DRF’s
OrderingFilter, and a pagination class. rind has the same four, and
this chapter takes them in that order.
All four are declared on the resource, and all four are described in the OpenAPI document without extra work.
Filtersets
A filterset is a struct whose fields are the filters of a list. Each
field is one query-string parameter. It is the equivalent of a
django-filter FilterSet, written as a Rust struct with a derive:
#![allow(unused)]
fn main() {
// sample/crates/network/network-api/src/stations/filters.rs
use network_models::{Region, Station};
use rind::FilterSet;
use rind::prelude::*;
#[derive(Debug, Default, FilterSet)]
#[filterset(model = Station)]
pub struct StationFilters {
#[filter(path = Station::status())]
pub status: Option<String>,
#[filter(path = Station::city())]
pub city: Option<String>,
/// Stations offering every one of these services.
#[filter(path = Station::services(), lookup = contains)]
pub services: Option<Vec<String>>,
#[filter(path = Station::platforms(), lookup = ge)]
pub min_platforms: Option<i64>,
/// Stations of a region, or of any region below it.
#[filter(method = in_region, alias = "in")]
pub region: Option<i64>,
#[filter(method = has_departures)]
pub has_departures: Option<bool>,
}
}
The resource names its filterset with filters = …:
#![allow(unused)]
fn main() {
// sample/crates/network/network-api/src/stations/views.rs
#[derive(Resource)]
#[resource(model = Station, path = "stations", out = StationOut,
filters = StationFilters, /* … */)]
pub struct StationResource;
}
A client then filters the list with the field names:
GET /stations?status=open&min_platforms=4
GET /stations?services=wifi,bar
The first request runs WHERE status = 'open' AND platforms >= 4. The
second keeps the stations whose services array holds both wifi and
bar. Filters add up: every filter the request uses must match.
Every field of a filterset is an Option. It is None when the request
does not use the filter, and the filter is then not applied. A field
without Option, or a field without #[filter(..)], does not compile.
How the value is read
The type inside the Option says how the parameter’s text is read:
String: the text as it is sent.bool:trueor1,falseor0(in any case).- a number (
i64,f64…) or a date (NaiveDate): parsed with the type’sFromStr.?day=2030-05-01reads aNaiveDate. Vec<…>of one of these: a comma-separated list.?status=planned,arrivedgivesvec!["planned", "arrived"]. Empty items are skipped (1,,2is[1, 2]).
A filter on a column: path and lookup
The most common filter compares a column with the value. path names
the column, through the model’s typed paths (Station::status()), and
lookup says how to compare. This is django-filter’s
filters.CharFilter(field_name="status", lookup_expr="exact").
Without a lookup, a single value is compared with = (eq), and a
list with IN (in):
#![allow(unused)]
fn main() {
// sample/crates/timetable/timetable-api/src/journeys/filters.rs
/// One of these statuses.
#[filter(path = Journey::status(), alias = "status")]
pub statuses: Option<Vec<String>>,
}
GET /journeys?status=planned,arrived
This runs WHERE status IN ('planned', 'arrived').
The other lookups compare differently: ge for “at least”, contains
for an array that holds every value, and so on. The full list is in
the lookups table at the end of this chapter.
A path can follow a foreign key, as in a query: any typed path of the model works.
A filter written as a function: method
Some filters are not a comparison: they need a sub-query, a join, or a
computation. For these, method names a function. The function receives
the list’s query and the value, and gives back the query, narrowed. This
is django-filter’s filters.BooleanFilter(method="has_departures").
#![allow(unused)]
fn main() {
// sample/crates/network/network-api/src/stations/filters.rs
/// `region`: the stations of the region and of every region below it.
pub fn in_region(q: Query<Station>, region: i64) -> Query<Station> {
let below = Region::descendants(region);
q.with(&below)
.join_cte(&below.r(), Station::region_id().eq(below.col::<i64>("id")))
}
/// `has_departures`: stations a journey leaves from (or none does).
pub fn has_departures(q: Query<Station>, value: bool) -> Query<Station> {
let leaving = Query::<Journey>::new()
.filter(Journey::origin_id().eq(Station::id().outer()))
.exists();
q.filter(if value { leaving } else { !leaving })
}
}
The value is passed by value for a number, a boolean or a date. A text is
lent as &str, and a list as a slice (&[i64]):
#![allow(unused)]
fn main() {
// sample/crates/timetable/timetable-api/src/journeys/filters.rs
pub fn through(q: Query<Journey>, stations: &[i64]) -> Query<Journey> { … }
}
A method is a plain function, not an async one. When it needs data
from the database first (an object by its id, say), it writes that
lookup as a sub-query of the query it returns, as has_departures does
above. The database runs everything in one statement.
Another name for a parameter: alias
alias = "…" gives a filter a second name. In the stations’ filterset,
?in=3 is the same as ?region=3. Both names are in the OpenAPI
document. You can repeat alias for more names.
When you want the parameter to have a different name from the field
(for example, a name that is a Rust keyword), use param = "…".
A filter that reads the other filters
A method declared with filters also receives the whole filterset, as
&Self. It can then read the values of the other filters. This is
useful when one filter only means something together with another:
#![allow(unused)]
fn main() {
// Not in the sample: a fragment.
#[filter(method = longer_than, filters)]
pub min_km: Option<f64>,
pub fn longer_than(q: Query<Journey>, km: f64, filters: &JourneyFilters) -> Query<Journey> {
match filters.origin {
Some(origin) => …,
None => q,
}
}
}
A filter that reads the request
A method declared with ctx also receives the request’s context,
&Ctx. It can read who is asking (ctx.user), which action runs
(ctx.action()), and the request’s typed parameters.
#![allow(unused)]
fn main() {
// sample/crates/booking/booking-api/src/reservations/filters.rs
use rind::api::Ctx;
/// `true`: only the reservations the user made.
#[filter(method = mine, ctx)]
pub mine: Option<bool>,
pub fn mine(q: Query<Reservation>, mine: bool, ctx: &Ctx) -> Query<Reservation> {
match ctx.user.as_ref() {
Some(user) if mine => q.filter(Reservation::booked_by_id().eq(user.id)),
_ => q,
}
}
}
Why make this a filter, and not part of a mode’s query? Because a filter is listed in the OpenAPI document, and a client can use it inside a nested list too. A mode’s query that read the query string by hand would be invisible to both.
With both filters and ctx, the function takes four arguments, in
this order: (query, value, filters, ctx).
In a nested list
(?fields=reservations_details(mine=1)), filters holds the nested
field’s filters, and ctx is still the whole request.
Coming from Django: a django-filter method can read
self.request.query_paramsfor any parameter it likes. A rind filter cannot read a parameter by its name. A value that is not a filter is a typed parameter, declared in a struct and read withctx.parameters::<P>(). This is what keeps the OpenAPI document complete.
What happens with wrong or missing values
rind follows django-filter here:
- An empty value is ignored:
?status=does not filter. - An unknown parameter is ignored:
?whatever=1does not filter, and is not an error. - A boolean that cannot be read leaves the filter off:
?has_departures=maybelists every station. - Any other value that cannot be read is a 400, which names the parameter. All the errors of the request come back together:
GET /stations?region=abc
{"region": ["Enter a number."]}
The errors come before the first query runs.
Filters apply to lists. A retrieve (GET /stations/1) ignores them.
Search
?search=… finds the rows where every term of the search appears in at
least one of the resource’s search fields. It is DRF’s SearchFilter
with its search_fields. Each #[search(..)] attribute on the resource
adds one field, with a mode that says how the term must match:
#![allow(unused)]
fn main() {
// sample/crates/network/network-api/src/stations/views.rs
#[search(Station::name(), unaccent)]
#[search(Station::code(), starts_with)]
pub struct StationResource;
}
GET /stations?search=gare rennes
This finds the stations whose name contains both “gare” and “rennes”,
in any case and with or without accents. A station whose code starts
with “RNS” is found by ?search=rns.
The value is split as DRF splits it: on spaces and on commas. A quoted
phrase ("train de nuit") stays one term. Each term must match at least
one field; a row is listed when every term matches.
% and _ in a search are plain characters, not SQL wildcards.
The search modes
A mode is the second argument of #[search(..)]. Without one, the mode
is contains.
| Mode | A term matches when… | DRF prefix |
|---|---|---|
contains | it is anywhere in the text, whatever the case | (none) |
starts_with | the text starts with it, whatever the case | ^ |
exact | it is the whole value, whatever the case | = |
unaccent | it is anywhere in the text, whatever the case and the accents (PostgreSQL’s unaccent extension) | & |
full_text | PostgreSQL’s full-text search finds it | @ |
unaccent_full_text | full-text search finds it, whatever the accents | # |
regex | the text matches it as a regular expression, whatever the case (~*) | $ |
The prefixes ^, =, @ and $ are DRF’s own. & and # come from a
real Django application that extended DRF’s search filter; rind keeps
them as modes.
A regular expression that the database cannot read is a 400. A regular expression runs as it is sent: on a large table, it reads every row.
Searching through a tree
A station belongs to a region, and regions form a tree (a country, its
regions, their departments). A search for “Bretagne” should find the
stations of Brittany, and also the stations of every department inside
it. tree(..) does this:
#![allow(unused)]
fn main() {
// sample/crates/network/network-api/src/stations/views.rs
#[search(tree(Station::region_id(), Region::name()), unaccent)]
}
The first argument is the row’s key to the tree (Station::region_id()).
The second is the tree’s column to search (Region::name()). A station
matches when its region’s name, or the name of any region above it,
matches the term, at any depth. rind walks the tree once per term
(Region::subtree_where).
Coming from Django: a Django project writes this as one search field per level:
region__name,region__parent__name,region__parent__parent__name… and stops at some depth. A tree search has no depth limit. See Trees.
Going further: how the case-insensitive modes are written
contains, starts_with, exact and unaccent are written the way
Django writes its case-insensitive lookups on PostgreSQL:
UPPER(field) LIKE UPPER('%term%'), not ILIKE. The rows found are the
same, except for a few rare letters (such as the Turkish dotted i). It
is also faster when the database’s locale is not C, because ILIKE
lowercases both sides on every row: 1.6 times faster on 475,000 French
communes in fr_FR.utf8.
An index that helps these searches is a trigram index on the same expression:
CREATE INDEX … USING gin (upper(name) gin_trgm_ops);
Ordering
?ordering=name sorts a list by a name; ?ordering=-name sorts it the
other way. This is DRF’s OrderingFilter. The resource says which names
a client may use (DRF’s ordering_fields), and the ordering to use when
the request gives none (DRF’s ordering):
#![allow(unused)]
fn main() {
// sample/crates/network/network-api/src/stations/views.rs
#[ordering(
by(id, name, code, platforms, departures = Station::departures().count()),
default("name")
)]
pub struct StationResource;
}
GET /stations?ordering=-platforms,name
This sorts by platforms, most first, then by name. Several names are separated by commas.
A name in by(..) is a column of the model, by default. With =, it is
any expression: departures = Station::departures().count() sorts by
the number of journeys that leave from the station.
A name that is not allowed is dropped, as DRF does. When no allowed name is left, the default ordering applies. An unknown name is never an error.
Coming from Django: there is no
Meta.orderingon the model. A resource says its default ordering with#[ordering(.., default("name"))].
Every ordering ends with the primary key
rind adds the primary key at the end of every ordering. This makes the order total: two rows never compare equal. Without it, two stations with the same name could swap places between two requests, and a client reading page 1 and then page 2 could see one of them twice, and miss another. With it, pages never overlap and never skip a row.
A name for the default only: hidden
Sometimes the default ordering needs a name that clients should not use.
In Django, this is ordering naming a field that ordering_fields does
not list. In rind, such a name goes in hidden(..), always with an
expression:
#![allow(unused)]
fn main() {
// A fragment: the stations by region name, then by name.
#[ordering(
by(id, name, code),
default("region__name", "name"),
hidden(region__name = Station::region().name())
)]
}
?ordering=region__name is then dropped like an unknown name, but the
default ordering still uses it.
An ordering that depends on the request
An ordering expression is given the request’s context, ctx. It can
read typed parameters, for
example to sort by distance to a point the request sends. When the
expression is an Option and is None for this request, the name is
dropped like an unknown one.
Pages
A list is always answered in pages. The answer has three parts: the
names of the paging parameters, where the page sits (nav), and the
rows (results):
GET /stations?page_size=2
{
"parameters": { "page": "page", "pagesize": "page_size" },
"nav": { "size": 2, "page": 1, "next": 2, "prev": null, "count": 6, "pages": 3 },
"results": [ … ]
}
?page=2asks for the second page.?page=lastasks for the last one.?page_size=20asks for 20 rows per page.countis the number of rows after the filters and the search, not the number of rows in the table.
A page that does not exist (?page=99, ?page=abc) gives the first
page, not an error. A page size that is missing, not a number, or not
positive gives the resource’s default size. A size larger than the
resource’s maximum is cut down to the maximum.
The default size is 100 rows, and the maximum is 50,000. A resource can change both:
#![allow(unused)]
fn main() {
#[resource(model = Station, path = "stations", out = StationOut,
page_size = 25, max_page_size = 1000)]
}
Coming from Django: this is DRF’s
PageNumberPaginationwithpage_size_query_param = "page_size"andmax_page_size, set once for every resource. The answer’s shape (parameters,nav,results) is the one of a real Django application’s custom pagination class, so its front end works unchanged. Unlike DRF, a page out of range is not a 404.
Reference
#[filterset(..)]
| Key | Meaning |
|---|---|
model = M | The model whose rows the filters narrow. Required. |
#[filter(..)]
Every field of a filterset has one, and its type is Option<T>.
| Key | Meaning |
|---|---|
path = M::col() | Compares this column (or path) with the value. |
lookup = … | How path compares: see the next table. Only with path. |
method = f | Calls f(query, value) instead. Either path or method, not both. |
filters | With method: f also takes the filterset, &Self. |
ctx | With method: f also takes the request, &Ctx (after filters). |
alias = "…" | One more name for the parameter. Repeatable. |
param = "…" | The parameter’s name, when it is not the field’s. |
description = "…" | The OpenAPI description, instead of the doc comment. "" gives none. |
A filter may not be named no_cache or nocache: those names belong to
the cache. No filter may share a name with another parameter
of the resource either (see
Parameters).
The lookups
lookup | SQL | Django lookup | Use |
|---|---|---|---|
eq (default for one value) | col = $1 | exact | |
in (default for a list) | col IN (…) | in | a Vec |
ne | col <> $1 | exclude(…) | |
lt, le, gt, ge | <, <=, >, >= | lt, lte, gt, gte | |
contains | col @> $1 | contains (array) | an array column holds every value |
overlap | col && $1 | overlap | an array column holds at least one value |
iexact | UPPER(col) = UPPER($1) | iexact | |
icontains | UPPER(col) LIKE UPPER('%term%') | icontains | % and _ in the value are plain characters |
istartswith | UPPER(col) LIKE UPPER('term%') | istartswith | the same |
under(Model, ..) | col IN (subtree) | — | a key to a tree model: the value’s rows and every row below them (Model::subtree) |
above(Model, ..) | col IN (ancestry) | — | a key to a tree model: the value’s rows and every row above them (Model::ancestry) |
The case-insensitive lookups are written as Django writes them on PostgreSQL, for the reasons given in the search section.
The tree lookups take the options of the tree walk after the model:
#![allow(unused)]
fn main() {
// sample/crates/network/network-api/src/stations/filters.rs
/// Stations of these regions, or of a region one level below them.
#[filter(path = Station::region_id(), lookup = under(Region, max_down = 1))]
pub regions_under: Option<Vec<i64>>,
}
| Lookup | Options |
|---|---|
under | max_down, down_to_level, at_level, include_self |
above | max_up, up_to_level, at_level, include_self |
#[search(..)]
#[search(path, mode)] or #[search(tree(key, tree_column), mode)],
repeatable. The modes are contains (the default), starts_with,
exact, unaccent, full_text, unaccent_full_text and regex.
#[ordering(..)]
| Key | Meaning |
|---|---|
by(a, b, c = expr) | The names a client may order by: a column of the model, or name = expression. |
default("a", "-b") | The ordering when the request gives none (or none allowed). |
hidden(name = expr) | Names only the default may use. |
Page parameters
| Parameter or key | Meaning |
|---|---|
?page=N, ?page=last | The page; out of range or unreadable gives page 1. |
?page_size=N | Rows per page, up to the maximum. |
#[resource(page_size = N)] | The default size (100). |
#[resource(max_page_size = N)] | The maximum size (50,000). It also limits an export. |