Answering as Django did: porting a Django application
This chapter is for one situation: you are replacing an existing Django application with rind, and its clients (a web front end, a mobile app, other services) must not notice the change. They must get the same JSON as before, and the existing database, with its data, must keep working as Django left it.
By default, rind answers in its own way. For example, it writes a date
and time with its time zone, and it lets the database’s foreign keys
decide what a deletion does. A Django application often does otherwise.
The django feature of rind, the module rind::django, gives you what
Django writes and rind does not do by default:
- local times without a zone, as Django writes them with
USE_TZ = False; - geometries as EWKT text, as a plain DRF serializer writes them;
- deletions that follow Django’s
on_deleterules, which live in Python and not in the database.
Other chapters cover the rest of what makes rind answer like Django; they are listed at the end.
To start a port from the Django database itself, see Starting from a database.
Turning it on
The module is behind a feature of the rind crate:
# Cargo.toml
[dependencies]
rind = { version = "…", features = ["django"] }
Local times
With USE_TZ = False, Django writes a timestamp with time zone column
as the naive local time of its TIME_ZONE setting: the time on a clock
in that zone, with no zone written. It adds the microseconds only when
there are some:
{"created": "2023-01-09T13:52:00", "updated": "2024-03-10T18:37:54.144655"}
rind writes a DateTime<Utc> with its zone. To answer as Django did, you
set the zone once, when the application starts, and convert the field in
the serializer with #[field(with = …)]:
#![allow(unused)]
fn main() {
// once, at start: Django's TIME_ZONE
rind::django::time::set_time_zone(rind::django::chrono_tz::Europe::Paris);
}
#![allow(unused)]
fn main() {
// in a serializer
#[field(with = rind::django::time::local)]
pub created: Option<rind::django::time::LocalDateTime>, // "2023-01-09T13:52:00"
}
local is for a column that is not null. For a nullable column, use
local_opt, and the field becomes an
Option<Option<LocalDateTime>>. Until set_time_zone is called, the
zone is UTC. Only the first call counts.
Reading local times sent by clients
Since Django’s clients receive local times, they also send local times
back. In an input, the type LocalDateTimeIn reads them:
#![allow(unused)]
fn main() {
// in an input, for a nullable column
pub datestart: Option<Option<rind::django::time::LocalDateTimeIn>>,
}
- A time without a zone (
2026-01-02T08:00:00, or without the seconds,2026-01-02T08:00) is read as a local time ofTIME_ZONE. - A time with its zone (
…+01:00,…Z) is read as that exact moment. - In both cases, the column’s
DateTime<Utc>is written. - Anything else is refused with DRF’s message:
Datetime has wrong format. Use one of these formats instead: ….
Coming from Django: here rind differs from Django on purpose. Django with
USE_TZ = Falseloses the zone of a time sent with one: DRF turns it into the naive time of UTC, which the database then reads as a local time (an hour or two early in Paris). rind keeps the moment that was sent.
Geometries
A plain DRF serializer (without rest_framework_gis) writes a GeoDjango
geometry as GEOS’s EWKT text: SRID=4326;POINT (2.35 48). To send the
same text, convert the field with one of the rind::django::ewkt
functions:
#![allow(unused)]
fn main() {
// in a serializer, for a nullable point column
#[field(with = rind::django::ewkt::point_ewkt)]
pub position: Option<Option<String>>, // "SRID=4326;POINT (2.35 48)"
}
point_ewktwrites a point.shape_ewktdoes the same for a column of any shape (a polygon, a line…). A shape rind cannot read is sent asnull.parse_pointreads a point that a client sends, as GeoDjango reads it: WKT (POINT(-1.55 47.21)) or EWKT withSRID=4326, longitude first. Another SRID is refused.
Numbers are written as short as they can be read back, as GEOS does. See Geography for rind’s own way of sending geometries.
Deleting as Django did
In a Django database, the foreign keys do nothing (NO ACTION). The
on_delete rules (CASCADE, SET_NULL, PROTECT…) are in the Python
code: Django’s collector finds the related rows and deletes or updates
them itself.
A port says so on each key, with in_code:
#![allow(unused)]
fn main() {
#[fk(Family, on_delete = cascade, in_code)]
pub family_id: i64,
}
The database key stays as it is, and rind’s deletion does what Django’s collector did (Models).
Some Django applications also write a safe_delete view: the deletion is
only tried, and the answer says what it would remove, unless the request
confirms it (?doit=really). rind has it ready made, because a native
application has the same use for it:
Tried first: safe_delete.
The tables that the port does not model still point to the ones it does, and a deletion must cascade into them too. You give them to rind as foreign tables.
Getting the deletion rules from Django
You do not copy the rules by hand: you ask Django for them. A script, run
in the application’s Django shell, writes rules.json. It only reads.
The file has one key per line: [table, column, target table, target column, rule].
RULES_OUT=rules.json python manage.py shell < on_delete_rules.py
The script is tools/django/on_delete_rules.py in rind’s repository:
# on_delete_rules.py: rind's tools/django/on_delete_rules.py
import collections
import json
import os
from django.apps import apps
rules = []
for model in apps.get_models(include_auto_created=True):
for field in model._meta.concrete_fields:
if not (field.is_relation and (field.many_to_one or field.one_to_one)):
continue
rules.append(
[
model._meta.db_table,
field.column,
field.remote_field.model._meta.db_table,
field.target_field.column,
field.remote_field.on_delete.__name__,
]
)
path = os.environ.get("RULES_OUT", "rules.json")
with open(path, "w") as out:
out.write("[\n" + ",\n".join(json.dumps(rule) for rule in sorted(rules)) + "\n]\n")
print(len(rules), "keys:", dict(collections.Counter(rule[4] for rule in rules)), "->", path)
It covers every concrete foreign key and one-to-one key, including those of the many-to-many link tables. Django’s rules become rind’s:
| Django | rind |
|---|---|
CASCADE | cascade |
SET_NULL | set_null |
PROTECT, RESTRICT | restrict (a 409 answer, where Django raises an error) |
DO_NOTHING | no_action (nothing is done) |
SET_DEFAULT, SET(..) | no equivalent |
Keep rules.json in the port’s repository, and run the script again when
the Django models change. Two commands use it:
rind inspect --apply plan.toml --rules rules.jsonwrites the rules on the models’ keys and on the foreign tables (Starting from a database).rind dbcheck --rules rules.jsonsays which keys of the application have another rule than the file’s.
Coming from Django: the
pre_deleteandpost_deletesignals are not sent for the rows that a deletion removes with it. Where they mattered, the port must do what they did by itself.
The rest
Other parts of rind also answer as Django does, and are explained in their own chapters:
- Case-insensitive lookups and searches are written as Django writes
them on PostgreSQL (
UPPER(…) LIKE UPPER(…)), not withILIKE: Filters. - The ids of a many-to-many field, as DRF’s
PrimaryKeyRelatedField(many=True)sends them:#[m2m_ids(hop = …)], Serializers. - Django’s
on_deleterules, applied by rind rather than by the database’s keys:#[fk(.., in_code)], Models. - The tokens the Django application already gave its users: rind-auth’s
verify_only, Signing in.