Field reference
Model fields are imported from @ghuri/orm (file fields from @ghuri/storage) and passed to
Model({ … }). See Models and fields for how they are used.
import { Model, CharField, ForeignKey, CASCADE } from '@ghuri/orm'
export class Post extends Model({ title: new CharField({ maxLength: 200 }), author: new ForeignKey(() => User, { onDelete: CASCADE }),}) {}Common options
Section titled “Common options”Accepted by every field.
| Option | Type | Default | Description |
|---|---|---|---|
null |
boolean |
false |
Store SQL NULL for missing values. The TypeScript type becomes T | null. |
blank |
boolean |
false |
Allow empty values in validation (serializers, admin forms). |
default |
T | () => T |
none | Default value, or a function called for each new instance. |
dbDefault |
value | none | Default emitted in the DDL (DEFAULT clause). |
choices |
Array<[value, label]> | enum object |
none | Restrict values (checked by fullClean()); the admin renders a select. |
primaryKey |
boolean |
false |
Make this the primary key. Implies null: false, unique: true. Disables the implicit id. |
unique |
boolean |
false |
Add a unique constraint. |
dbIndex |
boolean |
false |
Create an index on the column. |
dbColumn |
string |
snake_case of the name | Column name override. |
dbComment |
string |
none | Column comment (Postgres). |
editable |
boolean |
true |
false hides the field from the admin and from ModelSerializer writes. |
helpText |
string |
none | Shown in the admin and in OpenAPI descriptions. |
verboseName |
string |
derived from the name | Human-readable label. |
validators |
Validator[] |
[] |
Extra validators run by fullClean() and serializers. |
errorMessages |
Record<string, string> |
built-in | Override messages by code (null, blank, invalid, invalid_choice, unique, …). |
serialize |
boolean |
true |
false leaves the field out of dumpdata fixtures. |
Every model gets an implicit id: new BigAutoField({ primaryKey: true }) unless another field
sets primaryKey: true.
Field types
Section titled “Field types”“TS type” is the value type on model instances. Column types are what the schema editor emits.
Automatic primary keys
Section titled “Automatic primary keys”| Field | TS type | SQLite / D1 | Postgres |
|---|---|---|---|
AutoField |
number |
integer PRIMARY KEY AUTOINCREMENT |
integer GENERATED BY DEFAULT AS IDENTITY |
BigAutoField |
number |
integer PRIMARY KEY AUTOINCREMENT |
bigint GENERATED BY DEFAULT AS IDENTITY |
SmallAutoField |
number |
integer PRIMARY KEY AUTOINCREMENT |
smallint GENERATED BY DEFAULT AS IDENTITY |
Auto fields are not editable. Changing a model’s primary key or auto-field type is not
detected by makemigrations yet.
BigAutoField values are returned as JavaScript number. They are exact up to
Number.MAX_SAFE_INTEGER (about 9 × 1015), which no realistic auto-increment reaches.
| Field | TS type | SQLite / D1 | Postgres | Specific options |
|---|---|---|---|---|
CharField |
string |
varchar(maxLength) |
varchar(maxLength) |
maxLength (default 255) |
TextField |
string |
text |
text |
maxLength (validation only) |
SlugField |
string |
varchar(50) |
varchar(50) |
maxLength (default 50), allowUnicode; indexed by default |
EmailField |
string |
varchar(254) |
varchar(254) |
maxLength (default 254); EmailValidator |
URLField |
string |
varchar(200) |
varchar(200) |
maxLength (default 200); URLValidator |
UUIDField |
string |
char(36) |
uuid |
Use default: () => crypto.randomUUID() |
GenericIPAddressField |
string |
varchar(39) |
varchar(39) |
protocol: 'both' | 'IPv4' | 'IPv6', unpackIpv4 |
SQLite and D1 accept the varchar(n) declaration but do not enforce the length, so
maxLength is enforced by validation (fullClean(), serializers, the admin). Postgres
enforces it in the database too, which matters when you
move data from D1 to Postgres.
Numbers
Section titled “Numbers”| Field | TS type | SQLite / D1 | Postgres | Specific options |
|---|---|---|---|---|
IntegerField |
number |
integer |
integer |
|
BigIntegerField |
number |
bigint |
bigint |
|
SmallIntegerField |
number |
smallint |
smallint |
|
PositiveIntegerField |
number |
integer + CHECK >= 0 |
integer + CHECK >= 0 |
|
PositiveBigIntegerField |
number |
bigint + CHECK >= 0 |
bigint + CHECK >= 0 |
|
PositiveSmallIntegerField |
number |
smallint + CHECK >= 0 |
smallint + CHECK >= 0 |
|
FloatField |
number |
real |
double precision |
|
DecimalField |
string |
decimal(maxDigits, decimalPlaces) (NUMERIC affinity) |
numeric(maxDigits, decimalPlaces) |
maxDigits, decimalPlaces (DDL defaults 20 and 2) |
DecimalField values are strings ('19.99') so no precision is lost to floating point in
JavaScript. Use a decimal library if you need arithmetic. SQLite stores them with NUMERIC
affinity, which is exact only up to about 15 significant digits.
Booleans, dates and times
Section titled “Booleans, dates and times”| Field | TS type | SQLite / D1 | Postgres | Specific options |
|---|---|---|---|---|
BooleanField |
boolean |
integer (0/1) |
boolean |
|
NullBooleanField |
boolean | null |
integer (0/1) |
boolean |
Shorthand for BooleanField({ null: true, blank: true }) |
DateField |
string ('YYYY-MM-DD') |
text |
date |
autoNow, autoNowAdd |
DateTimeField |
Date |
text (ISO 8601, UTC) |
timestamp with time zone |
autoNow, autoNowAdd |
TimeField |
string ('HH:MM:SS') |
text |
time |
autoNow, autoNowAdd |
DurationField |
number (milliseconds) |
bigint |
bigint |
autoNowAdd sets the value when the row is created; autoNow sets it on every save().
Both make the field non-editable. QuerySet.update() does not touch autoNow fields, as in
Django.
Structured and binary data
Section titled “Structured and binary data”| Field | TS type | SQLite / D1 | Postgres | Specific options |
|---|---|---|---|---|
JSONField |
any (or your generic) |
text (JSON) |
jsonb |
|
BinaryField |
Uint8Array |
blob |
bytea |
not editable by default; base64 in fixtures |
Type a JSONField with a generic: new JSONField<{ theme: string }>({ default: () => ({ theme: 'light' }) }).
Files (@ghuri/storage)
Section titled “Files (@ghuri/storage)”| Field | TS type | SQLite / D1 | Postgres | Specific options |
|---|---|---|---|---|
FileField |
FieldFile |
varchar(100) |
varchar(100) |
uploadTo: string | (instance, filename) => string, storage (alias), maxLength (default 100) |
ImageField |
FieldFile |
varchar(100) |
varchar(100) |
as FileField; validates that uploads are images |
The column stores only the file name. FieldFile exposes name, url, size(), open(),
save(name, content) and delete(). See File storage and
Storage backends.
Relations
Section titled “Relations”| Field | TS type of the attribute | Column | Specific options |
|---|---|---|---|
ForeignKey |
obj.author: the related instance, awaitable (User | PromiseLike<User>); raw key at obj.authorId |
<name>_id, type of the target key; indexed |
to (first argument), onDelete (required), relatedName, relatedQueryName, toField, limitChoicesTo, dbConstraint |
OneToOneField |
as ForeignKey; reverse accessor returns one object |
<name>_id + unique |
as ForeignKey |
ManyToManyField |
related manager (obj.tags.all(), .add(), .remove(), .set(), .clear()) |
join table <table>_<name> (blog_post_tags) with <from>_id / <to>_id |
to, relatedName, relatedQueryName, through, throughFields, limitChoicesTo |
to is a model class, () => ModelClass, a string 'app_label.Model', or 'Model' for a
model in the same app. Use 'self' for self-referencing relations. The default reverse
accessor is <model>Set (user.postSet) with the lookup name <model> (post). See
Relations.
onDelete behaviours
Section titled “onDelete behaviours”Exported from @ghuri/orm. Deletes are emulated by the ORM rather than delegated to database
ON DELETE clauses, so they behave identically on D1, SQLite and Postgres.
| Constant | When the referenced row is deleted |
|---|---|
CASCADE |
Delete the referencing rows too (recursively, firing preDelete/postDelete). |
PROTECT |
Refuse; raise ProtectedError. |
RESTRICT |
Refuse unless the referencing rows are also being deleted in the same cascade (Django’s RESTRICT semantics). |
SET_NULL |
Set the key to NULL. The field needs null: true. |
SET_DEFAULT |
Set the key to the field’s default. |
SET(value) |
Set the key to value, or to the result of calling it when it is a function. |
DO_NOTHING |
Do nothing in the ORM. The database may reject the delete if it enforces the constraint. |
Because the rules live in the ORM, they apply to deletes made through it (instance.delete()
and QuerySet.delete(), which collects related objects first, exactly like Django). A raw SQL
DELETE bypasses them.
Validators
Section titled “Validators”Import from @ghuri/orm and pass in validators:
| Validator | Checks |
|---|---|
new MinValueValidator(n) |
value >= n |
new MaxValueValidator(n) |
value <= n |
new MinLengthValidator(n) |
length >= n |
new MaxLengthValidator(n) |
length <= n (added automatically for maxLength) |
new RegexValidator(regex, { message?, code?, inverseMatch?, flags? }) |
value matches (or does not match) the pattern |
new EmailValidator() |
a valid email address (used by EmailField) |
new URLValidator({ schemes?, message? }) |
a valid URL (used by URLField) |
new DecimalValidator(maxDigits, decimalPlaces) |
total and decimal digit counts (used by DecimalField) |
validateSlug, validateUnicodeSlug |
letters, numbers, underscores and hyphens (used by SlugField) |
validateEmail, validateURL |
function forms of the validators above |
validateIPv4Address, validateIPv6Address, validateIPv46Address |
IP addresses (used by GenericIPAddressField) |
import { IntegerField, MinValueValidator, MaxValueValidator } from '@ghuri/orm'
rating: new IntegerField({ validators: [new MinValueValidator(1), new MaxValueValidator(5)] }),A validator is a function (value) => void or an object with validate(value), and either
form throws ValidationError, so you can write your own:
import { ValidationError } from '@ghuri/core'
const noShouting = (value: string) => { if (value === value.toUpperCase()) throw new ValidationError('Please do not shout.')}The Field API
Section titled “The Field API”Admin, REST, agents and migrations rely on these public members. They are useful when you write
generic code over Model._meta.fields.
| Member | Description |
|---|---|
name, attname, column |
Property name, attribute holding the raw value (authorId for FKs), database column. |
model |
The model class the field belongs to. |
internalType |
'CharField', 'ForeignKey', … |
null, blank, primaryKey, unique, editable, choices, helpText, verboseName, maxLength |
Option values. |
isRelation, manyToOne, oneToOne, manyToMany, relatedModel |
Relation metadata. relatedModel resolves lazily. |
concrete |
true when the field has a column (false for ManyToManyField). |
hasDefault(), getDefault() |
Default handling. |
toPython(value) |
Coerce form or JSON input; throws ValidationError. |
validate(value, instance), clean(value, instance) |
Run built-in and custom validators; clean also coerces and returns the value. |
toDb(value, dialect), fromDb(value, dialect) |
Convert to and from the database representation. |
dbType(dialect) |
Column type for 'sqlite' or 'postgresql' (null for many-to-many). |
drizzleColumn(dialect) |
A Drizzle column builder for this field (escape hatch). |
deconstruct() |
JSON-able { type, options } used by migrations. |
formHint() |
Widget hint for the admin ('text', 'select', 'datetime', …). |
jsonSchema() |
JSON Schema fragment used by OpenAPI and agent tools. |