Skip to content

Field, FerroField and DbType

Fields are declared as type annotations on a Model, with Field(...) supplying database options (primary key, unique, index, defaults). The other entries on this page (FerroField, FerroNullable, varchar, DbType and DbTypeToken) describe the field metadata and the explicit column types db_type= takes. fn holds the database functions a generated column's expression or a check can call.

Field

Field(default: Any = PydanticUndefined, *, foreign_key: type[Any] | str | None | Any = _Unset, on_delete: OnDelete | Any = _Unset, primary_key: bool | Any = _Unset, autoincrement: bool | None | Any = _Unset, unique: bool | Any = _Unset, index: bool | Any = _Unset, nullable: FerroNullable | Any = _Unset, db_type: DbType | None | Any = _Unset, db_check: bool | Any = _Unset, renamed_from: str | None | Any = _Unset, retired: bool | Any = _Unset, generated: Callable[[Any], Any] | None | Any = _Unset, default_factory: Callable[[], Any] | Callable[[dict[str, Any]], Any] | None = _Unset, alias: str | None = _Unset, alias_priority: int | None = _Unset, validation_alias: str | AliasPath | AliasChoices | None = _Unset, serialization_alias: str | None = _Unset, title: str | None = _Unset, field_title_generator: Callable[[str, FieldInfo], str] | None = _Unset, description: str | None = _Unset, examples: list[Any] | None = _Unset, exclude: bool | None = _Unset, exclude_if: Callable[[Any], bool] | None = _Unset, discriminator: str | Discriminator | None = _Unset, deprecated: Deprecated | str | bool | None = _Unset, json_schema_extra: JsonDict | Callable[[JsonDict], None] | None = _Unset, frozen: bool | None = _Unset, validate_default: bool | None = _Unset, repr: bool = _Unset, init: bool | None = _Unset, init_var: bool | None = _Unset, kw_only: bool | None = _Unset, pattern: str | Pattern[str] | None = _Unset, strict: bool | None = _Unset, coerce_numbers_to_str: bool | None = _Unset, gt: SupportsGt | None = _Unset, ge: SupportsGe | None = _Unset, lt: SupportsLt | None = _Unset, le: SupportsLe | None = _Unset, multiple_of: float | None = _Unset, allow_inf_nan: bool | None = _Unset, max_digits: int | None = _Unset, decimal_places: int | None = _Unset, min_length: int | None = _Unset, max_length: int | None = _Unset, union_mode: Literal['smart', 'left_to_right'] = _Unset, fail_fast: bool | None = _Unset, **unknown: Any) -> Any

Declare a model field with Pydantic's options and Ferro's database options.

Field takes every argument of Pydantic's own Field and adds the database options Ferro reads: primary key, uniqueness, indexes, column type, foreign keys and rename hints. Use it as the field's default, or inside Annotated[...]. See Field options for each database option at work.

Parameters:

Name Type Description Default

default

Any

The value the field takes when it is not set.

PydanticUndefined

foreign_key

type[Any] | str | None | Any

Make the column a foreign key to this model's primary key: the class, or its class name for a self reference or a model defined later. The column's type must be the target key's type, and a type that stores differently needs the target's db_type. See Relationships.

_Unset

on_delete

OnDelete | Any

What the database does to this row when the row the key points at is deleted: "CASCADE" (the default), "RESTRICT", "SET NULL", "SET DEFAULT" or "NO ACTION". Needs foreign_key, and "SET NULL" needs an annotation that allows None.

_Unset

primary_key

bool | Any

Make the column the table's primary key.

_Unset

autoincrement

bool | None | Any

Whether the database generates the key. When not given, an integer primary key auto-increments.

_Unset

unique

bool | Any

Add a unique constraint on this column alone. For uniqueness across several columns, declare __ferro_composite_uniques__ on the model (see Composite uniques).

_Unset

index

bool | Any

Add an index on the column.

_Unset

nullable

FerroNullable | Any

"infer" (the default) makes the column nullable when the annotation allows None; True or False forces NULL or NOT NULL in every schema Ferro emits, whatever the annotation says.

_Unset

db_type

DbType | None | Any

The column's SQL type, overriding the one Ferro derives from the annotation: a DbTypeToken or a varchar(N) name. When not given, the column takes the derived type. A type the annotation cannot be stored as is refused when the class is defined.

_Unset

db_check

bool | Any

Add a CHECK constraint, named ck_<table>_<column>, that limits the column to an enum's values. Needs db_type, since the default native enum type already enforces them. Defaults to False.

_Unset

renamed_from

str | None | Any

The column's previous name, so that ferro migrate new renames the column, and every index and check named after it, instead of dropping and adding it. See Rename hints.

_Unset

retired

bool | Any

Take the column out of the model while it stays in the schema, nullable, until a later release deletes the declaration. The annotation must allow None. Defaults to False. See Retiring a column.

_Unset

generated

Callable[[Any], Any] | None | Any

A lambda over the model's own columns, its parameter named after the model, from which the database computes the column on every write: arithmetic and the functions in ferro.fn. The field defaults to None and holds the database's value once saved. Defaults to None, a plain column.

_Unset

default_factory

Callable[[], Any] | Callable[[dict[str, Any]], Any] | None

A callable to generate the default value. The callable can either take 0 arguments (in which case it is called as is) or a single argument containing the already validated data.

_Unset

alias

str | None

The name to use for the attribute when validating or serializing by alias. This is often used for things like converting between snake and camel case.

_Unset

alias_priority

int | None

Priority of the alias. This affects whether an alias generator is used.

_Unset

validation_alias

str | AliasPath | AliasChoices | None

Like alias, but only affects validation, not serialization.

_Unset

serialization_alias

str | None

Like alias, but only affects serialization, not validation.

_Unset

title

str | None

Human-readable title.

_Unset

field_title_generator

Callable[[str, FieldInfo], str] | None

A callable that takes a field name and returns title for it.

_Unset

description

str | None

Human-readable description.

_Unset

examples

list[Any] | None

Example values for this field.

_Unset

exclude

bool | None

Whether to exclude the field from the model serialization.

_Unset

exclude_if

Callable[[Any], bool] | None

A callable that determines whether to exclude a field during serialization based on its value.

_Unset

discriminator

str | Discriminator | None

Field name or Discriminator for discriminating the type in a tagged union.

_Unset

deprecated

Deprecated | str | bool | None

A deprecation message, an instance of warnings.deprecated or the typing_extensions.deprecated backport, or a boolean. If True, a default deprecation message will be emitted when accessing the field.

_Unset

json_schema_extra

JsonDict | Callable[[JsonDict], None] | None

A dict or callable to provide extra JSON schema properties.

_Unset

frozen

bool | None

Whether the field is frozen. If true, attempts to change the value on an instance will raise an error.

_Unset

validate_default

bool | None

If True, apply validation to the default value every time you create an instance. Otherwise, for performance reasons, the default value of the field is trusted and not validated.

_Unset

repr

bool

A boolean indicating whether to include the field in the __repr__ output.

_Unset

init

bool | None

Whether the field should be included in the constructor of the dataclass. (Only applies to dataclasses.)

_Unset

init_var

bool | None

Whether the field should only be included in the constructor of the dataclass. (Only applies to dataclasses.)

_Unset

kw_only

bool | None

Whether the field should be a keyword-only argument in the constructor of the dataclass. (Only applies to dataclasses.)

_Unset

coerce_numbers_to_str

bool | None

Whether to enable coercion of any Number type to str (not applicable in strict mode).

_Unset

strict

bool | None

If True, strict validation is applied to the field. See Strict Mode.

_Unset

gt

SupportsGt | None

Greater than. If set, value must be greater than this. Only applicable to numbers.

_Unset

ge

SupportsGe | None

Greater than or equal. If set, value must be greater than or equal to this. Only applicable to numbers.

_Unset

lt

SupportsLt | None

Less than. If set, value must be less than this. Only applicable to numbers.

_Unset

le

SupportsLe | None

Less than or equal. If set, value must be less than or equal to this. Only applicable to numbers.

_Unset

multiple_of

float | None

Value must be a multiple of this. Only applicable to numbers.

_Unset

min_length

int | None

Minimum length for iterables.

_Unset

max_length

int | None

Maximum length for iterables.

_Unset

pattern

str | Pattern[str] | None

Pattern for strings (a regular expression).

_Unset

allow_inf_nan

bool | None

Allow inf, -inf, nan. Only applicable to float and Decimal numbers.

_Unset

max_digits

int | None

Maximum number of allowed digits for strings.

_Unset

decimal_places

int | None

Maximum number of decimal places allowed for numbers.

_Unset

union_mode

Literal['smart', 'left_to_right']

The strategy to apply when validating a union. Can be smart (the default), or left_to_right. See Union Mode.

_Unset

fail_fast

bool | None

If True, validation will stop on the first error. If False, all validation errors will be collected. This option can be applied only to iterable types (list, tuple, set, and frozenset).

_Unset

**unknown

Any

Refused: a keyword not listed here raises TypeError naming the closest one that is. A relation keyword Field no longer takes (back_ref, many_to_many, related_name, through, reverse_index) names what replaces it; see Upgrading.

{}

Returns:

Type Description
Any

A new FieldInfo that carries the database options in its metadata, as one FerroField, and never in its JSON schema. The return annotation is Any so that Field type-checks as any field's default.

Raises:

Type Description
TypeError

A keyword Field does not take, or nullable, renamed_from, retired, generated, foreign_key or on_delete has a value of the wrong type.

Examples:

from ferro import Field, Model, create_tables


class Reader(Model):
    id: int | None = Field(default=None, primary_key=True)
    handle: str = Field(unique=True, min_length=3)
    nickname: str | None = Field(default=None, index=True)


await create_tables()
reader = await Reader.create(handle="ada")
assert reader.id == 1

The same model with the options inside Annotated:

from typing import Annotated

from ferro import Field, Model


class Reader(Model):
    id: Annotated[int | None, Field(primary_key=True)] = None
    handle: Annotated[str, Field(unique=True, min_length=3)]
    nickname: Annotated[str | None, Field(index=True)] = None

FerroField

FerroField(primary_key: bool = False, autoincrement: bool | None = None, unique: bool = False, index: bool = False, nullable: FerroNullable = 'infer', db_type: DbType | None = None, db_check: bool = False, renamed_from: str | None = None, retired: bool = False, generated: Any = None, foreign_key: type | str | None = None, on_delete: OnDelete | None = None)

Database options for one model field, given inside Annotated[...].

Field takes the same options and is the usual spelling: it stores them as one FerroField in the field's metadata, never in its JSON schema. FerroField carries only the database options, for an Annotated declaration that keeps them apart from Pydantic's own Field. See Field options for each option at work.

Examples:

from typing import Annotated

from ferro import FerroField, Model, create_tables


class Tag(Model):
    id: Annotated[int | None, FerroField(primary_key=True)] = None
    label: Annotated[str, FerroField(unique=True, index=True)]


await create_tables()
tag = await Tag.create(label="history")
assert tag.id == 1

Parameters:

Name Type Description Default
primary_key bool

Make the column the table's primary key.

False
autoincrement bool | None

Whether the database generates the key. Defaults to None, which lets an integer primary key auto-increment.

None
unique bool

Add a unique constraint on this column alone. For uniqueness across several columns, declare __ferro_composite_uniques__ on the model (see Composite uniques).

False
index bool

Add an index on the column.

False
nullable FerroNullable

"infer" (the default) makes the column nullable when the annotation allows None; True or False forces NULL or NOT NULL whatever the annotation says.

'infer'
db_type DbType | None

The column's SQL type, overriding the one Ferro derives from the annotation: a DbTypeToken or a varchar(N) name. Defaults to None, the derived type. A type the annotation cannot be stored as is refused when the class is defined.

None
db_check bool

Add a CHECK constraint that limits the column to an enum's values. Needs db_type, since the default native enum type already enforces them. Defaults to False.

False
renamed_from str | None

The column's previous name, so that ferro migrate new renames the column instead of dropping and adding it. See Rename hints.

None
retired bool

Take the column out of the model while it stays in the schema, nullable, until a later release deletes the declaration. The annotation must allow None. Defaults to False. See Retiring a column.

False
generated Any

A lambda over the model's own columns from which the database computes the column on every write. Defaults to None, a plain column. Give the field a None default beside it, as Field does for you.

None
foreign_key type | str | None

The model whose primary key the column holds: the class, or its class name for a self reference or a model defined later. Defaults to None, a plain column.

None
on_delete OnDelete | None

What the database does to this row when the row the key points at is deleted: "CASCADE", "RESTRICT", "SET NULL", "SET DEFAULT" or "NO ACTION". Defaults to None, which is "CASCADE" on a foreign-key column.

None

Raises:

Type Description
TypeError

nullable, renamed_from, retired, generated, foreign_key or on_delete has a value of the wrong type.

Attributes:

Name Type Description
primary_key

Whether the column is the table's primary key.

autoincrement

Whether the database generates the key; None lets Ferro decide.

unique

Whether the column has a single-column unique constraint.

index

Whether the column has an index.

nullable

"infer", or a forced True or False.

db_type

The SQL type override, or None for the derived type.

db_check

Whether the column has a CHECK constraint on an enum's values.

renamed_from

The column's previous name, or None.

retired

Whether the column is retired from the model.

generated

The lambda the database computes the column from, or None.

foreign_key

The model the column's key points at, its class name, or None.

on_delete str | None

The referential action on a foreign-key column, or None when unset.

primary_key instance-attribute

primary_key = primary_key

Whether the column is the table's primary key.

autoincrement instance-attribute

autoincrement = autoincrement

Whether the database generates the key; None lets Ferro decide.

unique instance-attribute

unique = unique

Whether the column has a single-column unique constraint.

index instance-attribute

index = index

Whether the column has an index.

nullable instance-attribute

nullable = _validate_nullable_option(nullable, 'FerroField')

"infer", or a forced True or False.

db_type instance-attribute

db_type = db_type

The SQL type override, or None for the derived type.

db_check instance-attribute

db_check = db_check

Whether the column has a CHECK constraint on an enum's values.

renamed_from instance-attribute

renamed_from = _validate_renamed_from(renamed_from, 'FerroField')

The column's previous name, or None.

retired instance-attribute

retired = _validate_retired(retired, 'FerroField')

Whether the column is retired from the model.

generated instance-attribute

generated = _validate_generated(generated, 'FerroField')

The lambda the database computes the column from, or None.

foreign_key instance-attribute

foreign_key = _validate_foreign_key(foreign_key, 'FerroField')

The model the column's key points at, its class name, or None.

on_delete instance-attribute

on_delete: str | None = 'CASCADE' if on_delete is None and foreign_key is not None else on_delete

The referential action on a foreign-key column, or None when unset.

A foreign-key column declared without one holds "CASCADE".

FerroNullable module-attribute

FerroNullable = Literal['infer'] | bool

Column nullability: "infer" follows the annotation, True or False forces it.

With "infer", a column is nullable when its annotation allows None. True and False force NULL and NOT NULL in every schema Ferro emits, whatever the annotation says.

varchar

varchar(length: int) -> str

Build the varchar(N) type name for db_type=.

A call to varchar reads as a deliberate type choice, where a raw "varchar(80)" string could be a typo. Ferro still checks the value against the field's annotation when the model class is defined.

Parameters:

Name Type Description Default
length int

The maximum length in characters. Must be positive.

required

Returns:

Type Description
str

The type name, "varchar(<length>)".

Raises:

Type Description
ValueError

length is zero or negative.

Examples:

from ferro import varchar

assert varchar(80) == "varchar(80)"

DbType module-attribute

DbType = DbTypeToken | str

A db_type= value: a DbTypeToken or a varchar(N) string.

Build the varchar(N) form with varchar.

DbTypeToken module-attribute

DbTypeToken = Literal['text', 'smallint', 'int', 'bigint', 'uuid', 'timestamp', 'timestamptz', 'date', 'time', 'json', 'jsonb']

SQL storage type names accepted by db_type= on Field.

See Column type overrides with db_type for the types each name maps to on SQLite and Postgres.

fn

SQL functions for a generated column's expression.

Each function here is one the database evaluates, with the same result on SQLite and Postgres. Call it on a column inside a Field(generated=...) lambda, or on either side of a Check comparison; it builds an expression the database computes, never a Python value. An expression combines these functions with columns, literals, + - * / and unary -. Generated columns lists the rules an expression must follow to store the same value on both databases.

Examples:

from ferro import Field, Model, create_tables, fn


class Transaction(Model):
    id: int | None = Field(default=None, primary_key=True)
    amount_minor: int
    direction: int = Field(
        generated=lambda transaction: fn.sign(transaction.amount_minor)
    )


await create_tables()
transaction = await Transaction.create(amount_minor=-250)
assert transaction.direction == -1

Functions:

Name Description
sign

Return -1, 0 or 1 by the sign of a number.

abs

Return a number without its sign.

least

Return the smallest of two or more numbers or dates.

greatest

Return the largest of two or more numbers or dates.

coalesce

Return the first argument that is not NULL.

length

Return the number of characters in a text.

year

Return the year of a date.

month

Return the month of a date, from 1 to 12.

day

Return the day of the month of a date, from 1 to 31.

sign

sign(value: Any) -> Any

Return -1, 0 or 1 by the sign of a number.

Parameters:

Name Type Description Default
value Any

An integer, float or decimal column or expression.

required

Returns:

Type Description
Any

The expression the database computes, of the argument's type: -1 for a negative value, 0 for zero and 1 for a positive one.

abs

abs(value: Any) -> Any

Return a number without its sign.

Parameters:

Name Type Description Default
value Any

An integer, float or decimal column or expression.

required

Returns:

Type Description
Any

The expression the database computes, of the argument's type.

least

least(first: Any, second: Any, *more: Any) -> Any

Return the smallest of two or more numbers or dates.

Every argument must be non-nullable, since the two databases disagree on a NULL; wrap a nullable column in coalesce. Text is not accepted: Postgres orders it by collation and SQLite byte by byte.

Parameters:

Name Type Description Default
first Any

An integer, float, decimal or date column or expression.

required
second Any

A value of the same type.

required
*more Any

More values of the same type.

()

Returns:

Type Description
Any

The expression the database computes, of the arguments' type.

greatest

greatest(first: Any, second: Any, *more: Any) -> Any

Return the largest of two or more numbers or dates.

Every argument must be non-nullable, as for least.

Parameters:

Name Type Description Default
first Any

An integer, float, decimal or date column or expression.

required
second Any

A value of the same type.

required
*more Any

More values of the same type.

()

Returns:

Type Description
Any

The expression the database computes, of the arguments' type.

coalesce

coalesce(first: Any, second: Any, *more: Any) -> Any

Return the first argument that is not NULL.

Parameters:

Name Type Description Default
first Any

An integer, float, decimal, text, date or datetime column or expression.

required
second Any

A value of the same type, such as a literal fallback.

required
*more Any

More values of the same type.

()

Returns:

Type Description
Any

The expression the database computes, of the arguments' type. It is NULL only when every argument is.

length

length(value: Any) -> Any

Return the number of characters in a text.

Parameters:

Name Type Description Default
value Any

A text column or expression.

required

Returns:

Type Description
Any

The expression the database computes, an integer.

year

year(value: Any) -> Any

Return the year of a date.

Parameters:

Name Type Description Default
value Any

A date column. A datetime is refused: its year depends on the session's time zone.

required

Returns:

Type Description
Any

The expression the database computes, an integer.

month

month(value: Any) -> Any

Return the month of a date, from 1 to 12.

Parameters:

Name Type Description Default
value Any

A date column. A datetime is refused: its month depends on the session's time zone.

required

Returns:

Type Description
Any

The expression the database computes, an integer.

day

day(value: Any) -> Any

Return the day of the month of a date, from 1 to 31.

Parameters:

Name Type Description Default
value Any

A date column. A datetime is refused: its day depends on the session's time zone.

required

Returns:

Type Description
Any

The expression the database computes, an integer.