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 |
|---|---|---|---|
|
Any
|
The value the field takes when it is not set. |
PydanticUndefined
|
|
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
|
_Unset
|
|
OnDelete | Any
|
What the database does to this row when the row the key
points at is deleted: |
_Unset
|
|
bool | Any
|
Make the column the table's primary key. |
_Unset
|
|
bool | None | Any
|
Whether the database generates the key. When not given, an integer primary key auto-increments. |
_Unset
|
|
bool | Any
|
Add a unique constraint on this column alone. For uniqueness
across several columns, declare |
_Unset
|
|
bool | Any
|
Add an index on the column. |
_Unset
|
|
FerroNullable | Any
|
|
_Unset
|
|
DbType | None | Any
|
The column's SQL type, overriding the one Ferro derives from
the annotation: a |
_Unset
|
|
bool | Any
|
Add a |
_Unset
|
|
str | None | Any
|
The column's previous name, so that |
_Unset
|
|
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 |
_Unset
|
|
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
|
_Unset
|
|
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
|
|
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
|
|
int | None
|
Priority of the alias. This affects whether an alias generator is used. |
_Unset
|
|
str | AliasPath | AliasChoices | None
|
Like |
_Unset
|
|
str | None
|
Like |
_Unset
|
|
str | None
|
Human-readable title. |
_Unset
|
|
Callable[[str, FieldInfo], str] | None
|
A callable that takes a field name and returns title for it. |
_Unset
|
|
str | None
|
Human-readable description. |
_Unset
|
|
list[Any] | None
|
Example values for this field. |
_Unset
|
|
bool | None
|
Whether to exclude the field from the model serialization. |
_Unset
|
|
Callable[[Any], bool] | None
|
A callable that determines whether to exclude a field during serialization based on its value. |
_Unset
|
|
str | Discriminator | None
|
Field name or Discriminator for discriminating the type in a tagged union. |
_Unset
|
|
Deprecated | str | bool | None
|
A deprecation message, an instance of |
_Unset
|
|
JsonDict | Callable[[JsonDict], None] | None
|
A dict or callable to provide extra JSON schema properties. |
_Unset
|
|
bool | None
|
Whether the field is frozen. If true, attempts to change the value on an instance will raise an error. |
_Unset
|
|
bool | None
|
If |
_Unset
|
|
bool
|
A boolean indicating whether to include the field in the |
_Unset
|
|
bool | None
|
Whether the field should be included in the constructor of the dataclass. (Only applies to dataclasses.) |
_Unset
|
|
bool | None
|
Whether the field should only be included in the constructor of the dataclass. (Only applies to dataclasses.) |
_Unset
|
|
bool | None
|
Whether the field should be a keyword-only argument in the constructor of the dataclass. (Only applies to dataclasses.) |
_Unset
|
|
bool | None
|
Whether to enable coercion of any |
_Unset
|
|
bool | None
|
If |
_Unset
|
|
SupportsGt | None
|
Greater than. If set, value must be greater than this. Only applicable to numbers. |
_Unset
|
|
SupportsGe | None
|
Greater than or equal. If set, value must be greater than or equal to this. Only applicable to numbers. |
_Unset
|
|
SupportsLt | None
|
Less than. If set, value must be less than this. Only applicable to numbers. |
_Unset
|
|
SupportsLe | None
|
Less than or equal. If set, value must be less than or equal to this. Only applicable to numbers. |
_Unset
|
|
float | None
|
Value must be a multiple of this. Only applicable to numbers. |
_Unset
|
|
int | None
|
Minimum length for iterables. |
_Unset
|
|
int | None
|
Maximum length for iterables. |
_Unset
|
|
str | Pattern[str] | None
|
Pattern for strings (a regular expression). |
_Unset
|
|
bool | None
|
Allow |
_Unset
|
|
int | None
|
Maximum number of allowed digits for strings. |
_Unset
|
|
int | None
|
Maximum number of decimal places allowed for numbers. |
_Unset
|
|
Literal['smart', 'left_to_right']
|
The strategy to apply when validating a union. Can be |
_Unset
|
|
bool | None
|
If |
_Unset
|
|
Any
|
Refused: a keyword not listed here raises |
{}
|
Returns:
| Type | Description |
|---|---|
Any
|
A new |
Raises:
| Type | Description |
|---|---|
TypeError
|
A keyword |
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
|
unique
|
bool
|
Add a unique constraint on this column alone. For
uniqueness across several columns, declare
|
False
|
index
|
bool
|
Add an index on the column. |
False
|
nullable
|
FerroNullable
|
|
'infer'
|
db_type
|
DbType | None
|
The column's SQL type, overriding the one Ferro derives
from the annotation: a |
None
|
db_check
|
bool
|
Add a |
False
|
renamed_from
|
str | None
|
The column's previous name, so that
|
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 |
False
|
generated
|
Any
|
A lambda over the model's own columns from which the
database computes the column on every write. Defaults to
|
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
|
on_delete
|
OnDelete | None
|
What the database does to this row when the row the
key points at is deleted: |
None
|
Raises:
| Type | Description |
|---|---|
TypeError
|
|
- Reference Python API
Attributes:
| Name | Type | Description |
|---|---|---|
primary_key |
Whether the column is the table's primary key. |
|
autoincrement |
Whether the database generates the key; |
|
unique |
Whether the column has a single-column unique constraint. |
|
index |
Whether the column has an index. |
|
nullable |
|
|
db_type |
The SQL type override, or |
|
db_check |
Whether the column has a |
|
renamed_from |
The column's previous name, or |
|
retired |
Whether the column is retired from the model. |
|
generated |
The lambda the database computes the column from, or |
|
foreign_key |
The model the column's key points at, its class name, or |
|
on_delete |
str | None
|
The referential action on a foreign-key column, or |
primary_key
instance-attribute
¶
Whether the column is the table's primary key.
autoincrement
instance-attribute
¶
Whether the database generates the key; None lets Ferro decide.
unique
instance-attribute
¶
Whether the column has a single-column unique constraint.
nullable
instance-attribute
¶
"infer", or a forced True or False.
db_check
instance-attribute
¶
Whether the column has a CHECK constraint on an enum's values.
renamed_from
instance-attribute
¶
The column's previous name, or None.
retired
instance-attribute
¶
Whether the column is retired from the model.
generated
instance-attribute
¶
The lambda the database computes the column from, or None.
foreign_key
instance-attribute
¶
The model the column's key points at, its class name, or None.
FerroNullable
module-attribute
¶
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.
- Reference Python API Field, FerroField and DbType
varchar
¶
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, |
Raises:
| Type | Description |
|---|---|
ValueError
|
|
Examples:
- Reference Python API Field, FerroField and DbType
DbType
module-attribute
¶
DbType = DbTypeToken | str
A db_type= value: a DbTypeToken or a varchar(N) string.
Build the varchar(N) form with varchar.
- Reference Python API Field, FerroField and DbType
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.
- Reference Python API Field, FerroField and DbType
-
Reference
Python API
Field, FerroField and DbType
DbType
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
-
Reference
Python API
Field, FerroField and DbType
Field
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 |
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
¶
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: |
abs
¶
least
¶
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. |
-
Reference
Python API
Field, FerroField and DbType
fngreatest
greatest
¶
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
¶
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
|
-
Reference
Python API
Field, FerroField and DbType
fnleast