Conditions
filter keeps the rows that match a condition. This page shows how
conditions are written: comparisons on a path, NULL, lists of values,
and how conditions combine. It is the part of Django’s documentation
called “field lookups”, and the Q objects.
A comparison
#![allow(unused)]
fn main() {
Query::<Station>::new().filter(Station::status().eq("open"))
}
WHERE "t0"."status" = $1
-- params: [Text("open")]
Station::status() is a path to a column, and .eq("open") compares it
with a value. The result is a condition: a value of type Cond, which
filter takes.
The comparisons are:
| Method | SQL | Django lookup |
|---|---|---|
eq(v) | = v | exact (the default) |
ne(v) | <> v | exclude(field=v), but see NULL |
lt(v), le(v) | < v, <= v | lt, lte |
gt(v), ge(v) | > v, >= v | gt, gte |
in_(values) | IN (…) | in |
is_null(), is_not_null() | IS NULL, IS NOT NULL | isnull=True, isnull=False |
distinct_from(v), not_distinct_from(v) | IS DISTINCT FROM v, IS NOT DISTINCT FROM v |
There is no range lookup: write ge(a) & lt(b). Lookups on texts,
arrays and JSON (icontains, contains, has_key…) have a page of
their own: Lookups.
What a path compares with
A path compares with a value of its type, with another path, or with an expression:
#![allow(unused)]
fn main() {
Station::platforms().ge(10) // a value
Journey::arrives_at().gt(Journey::departs_at()) // another column
(Station::platforms() * 2).gt(30) // an expression
Journey::departs_at().gt(func::now()) // an SQL function
}
WHERE "t0"."arrives_at" > "t0"."departs_at"
WHERE ("t0"."platforms" * $1) > $2
WHERE "t0"."departs_at" > NOW()
The types must agree, or the code does not compile:
error[E0277]: the trait bound `{integer}: Operand<std::string::String>` is not satisfied
|
| Station::status().eq(3)
| -- ^ the trait `Operand<std::string::String>` is not implemented for `{integer}`
What counts as “the same type”:
| Column | Compares with |
|---|---|
i16, i32, i64 | any integer (the path of any integer column is a Path<i64>) |
f32, f64 | any float |
String | &str, String |
bool | bool |
NaiveDate, DateTime<Utc>, NaiveDateTime | a value of the same chrono type |
Vec<String>, Vec<i64>… | a Vec of the same type |
Option<T> | a T, or an Option<T> |
| a type of your own | a value of that type (Types of your own) |
Dates and times
Dates compare like numbers. A day, from midnight to midnight:
#![allow(unused)]
fn main() {
let day = DateTime::parse_from_rfc3339("2030-05-01T00:00:00Z")?.with_timezone(&Utc);
Query::<Journey>::new().filter(
Journey::departs_at().ge(day) & Journey::departs_at().lt(day + chrono::Duration::days(1)),
)
// journeys 1 and 2
}
There are no __year, __month or __date lookups. Compare with a
range of moments as above (an index on the column serves it), or write
the function with an expression template:
#![allow(unused)]
fn main() {
// Django: filter(departs_at__month=5)
Query::<Journey>::new()
.filter(Journey::departs_at().expr().wrap::<i64>("EXTRACT(MONTH FROM {})::bigint").eq(5))
// WHERE EXTRACT(MONTH FROM "t0"."departs_at")::bigint = $1 → journeys 1, 2, 4
}
A moment has no day by itself: it depends on the time zone. Journey 2 leaves on 1 May at 22:00 UTC, which is 2 May in Paris:
#![allow(unused)]
fn main() {
Journey::departs_at().expr().wrap::<NaiveDate>("({} AT TIME ZONE 'Europe/Paris')::date")
// J100 → 2030-05-01, J200 → 2030-05-02
}
Combining conditions: &, |, !
Conditions combine with Rust’s operators: & (and), | (or) and !
(not). They are Django’s Q objects.
#![allow(unused)]
fn main() {
Query::<Station>::new().filter(
Station::status().eq("open") & (Station::city().eq("Paris") | Station::platforms().ge(10)),
)
}
WHERE "t0"."status" = $1 AND ("t0"."city" = $2 OR "t0"."platforms" >= $3)
-- params: [Text("open"), Text("Paris"), Int(10)]
Stations 1, 2, 5 and 6. The parentheses in Rust are the parentheses in
SQL: & binds tighter than | in both, but write them when you mix the
two.
#![allow(unused)]
fn main() {
Query::<Station>::new().filter(!Station::status().eq("open"))
// WHERE NOT ("t0"."status" = $1) → station 4
}
Calling filter several times also combines with and:
#![allow(unused)]
fn main() {
Query::<Station>::new()
.filter(Station::status().eq("open"))
.filter(Station::platforms().ge(10))
// WHERE "t0"."status" = $1 AND "t0"."platforms" >= $2
}
This is the usual way to build a query step by step: a scope gives the base, each caller adds its filters.
Conditions are values too. A function can build one, and it can be reused:
#![allow(unused)]
fn main() {
impl Loan {
pub fn is_out() -> Cond {
Loan::returned_on().is_null()
}
}
Query::<Loan>::new().filter(Loan::is_out() & Loan::borrower_id().eq(user.id))
}
Cond::Const(true) and Cond::Const(false) are the conditions that
always and never match: a start for a condition built in a loop.
#![allow(unused)]
fn main() {
let mut any_city = Cond::Const(false);
for city in ["Paris", "Brest"] {
any_city = any_city | Station::city().eq(city);
}
}
(For this case, in_ is shorter.)
Lists of values: in_
#![allow(unused)]
fn main() {
Station::code().in_(["PAR", "REN", "BRE"])
// WHERE "t0"."code" IN ($1, $2, $3) → stations 1, 2, 3
}
in_ takes anything that iterates over values of the path’s type: an
array, a Vec, a range (Station::id().in_(1..=10)), an iterator
(ids.iter().copied()).
An empty list matches nothing. rind writes WHERE FALSE rather than
IN (), which is not valid SQL:
#![allow(unused)]
fn main() {
Station::code().in_(Vec::<&str>::new())
// WHERE FALSE → no row
}
A long list is one parameter. PostgreSQL takes at most 65,535 parameters in one statement, and a real application goes past it (the ids of 70,000 places on a map). Beyond 1,000 values, rind sends the list as one array parameter:
#![allow(unused)]
fn main() {
Station::id().in_(1..=1500)
// WHERE "t0"."id" = ANY($1) -- one parameter: an array of 1500 numbers
}
It plans as fast as the list. You have nothing to do.
For a list that comes from another query, use a
sub-query: Station::id().in_sub(…).
NULL
SQL has a third truth value: unknown. Any comparison with NULL is
unknown, and WHERE keeps only the rows where the condition is true.
rind writes the SQL you ask for, so you meet these rules directly. Here
they are, with the sample’s stations: Brest, Quimper and Toulouse have no
opening date (opened is NULL); only Paris and Rennes have a manager
(manager_id is 2), the four others have none.
Testing for NULL: is_null
#![allow(unused)]
fn main() {
Station::opened().is_null() // WHERE "t0"."opened" IS NULL → 3, 4, 5
Station::opened().is_not_null() // WHERE "t0"."opened" IS NOT NULL → 1, 2, 6
}
This is Django’s opened__isnull=True. It is the only correct way to
look for a NULL.
eq(None) matches nothing
#![allow(unused)]
fn main() {
let none: Option<NaiveDate> = None;
Station::opened().eq(none)
// WHERE "t0"."opened" = NULL → no row
}
Django turns filter(opened=None) into IS NULL. rind writes = NULL,
which is never true. Use is_null(), or not_distinct_from below when
the value may or may not be None.
ne leaves out the NULLs
#![allow(unused)]
fn main() {
Station::manager_id().ne(2)
// WHERE "t0"."manager_id" <> $1 → no row!
}
The four stations without a manager are not “not managed by 2”: for SQL,
NULL <> 2 is unknown, so they go. Django’s exclude(manager=2) keeps
them. To keep them in rind, say that NULL is different from 2:
#![allow(unused)]
fn main() {
Station::manager_id().distinct_from(2)
// WHERE "t0"."manager_id" IS DISTINCT FROM $1 → 3, 4, 5, 6
}
or use exclude, which keeps the rows
where the condition is false or unknown.
Comparing with a value that may be None
distinct_from and not_distinct_from treat NULL as an ordinary
value: two NULLs are equal, and NULL differs from everything else.
They are what you want when the value comes from the program and may be
None:
#![allow(unused)]
fn main() {
fn same_opening(day: Option<NaiveDate>) -> Cond {
Station::opened().not_distinct_from(day)
}
// same_opening(None) → WHERE "t0"."opened" IS NOT DISTINCT FROM NULL → 3, 4, 5
}
Summary
| You want | Write | Not |
|---|---|---|
| the column is empty | is_null() | eq(None) |
| the column has a value | is_not_null() | ne(None) |
| the column is not 2, empty included | distinct_from(2), or exclude(eq(2)) | ne(2) |
the column equals a value that may be None | not_distinct_from(value) | eq(value) |
A comparison through a nullable foreign key has the same rules: see Relations.
Conditions are checked against the query’s model
A path belongs to a model. A condition on another model than the query’s
is refused when the SQL is built (by to_sql, or by the Db before it
sends anything):
#![allow(unused)]
fn main() {
Query::<Journey>::new().filter(Station::city().eq("Paris"))
}
the path to `city` starts from `network_station` but the query is on `timetable_journey`;
to refer to the enclosing query, use `.outer()`
To reach another model, go through a relation
(Journey::origin().city()), or use a sub-query.