Skip to content

Foreign Keys (Legacy Mode)

This page documents the legacy-mode foreign key support. For the ORM-mode ForeignKey descriptor with lazy loading, see ORM Mode.

Source: sqliter/model/foreign_key.py

See also: Guide -- Foreign Keys, Explicit Foreign Keys


FKAction

Type alias for the allowed foreign key actions.

FKAction = Literal["CASCADE", "SET NULL", "RESTRICT", "NO ACTION"]
ValueDescription
"CASCADE"Propagate the operation to referencing records (delete or update them)
"SET NULL"Set the foreign key field to NULL (requires null=True)
"RESTRICT"Prevent the operation if references exist (default)
"NO ACTION"Similar to RESTRICT in SQLite

ForeignKey()

Factory function that creates a Pydantic Field with foreign key metadata stored in json_schema_extra.

def ForeignKey(
    to: type[BaseDBModel],
    *,
    on_delete: FKAction = "RESTRICT",
    on_update: FKAction = "RESTRICT",
    null: bool = False,
    unique: bool = False,
    related_name: str | None = None,
    db_column: str | None = None,
    default: Any = ...,
    **kwargs: Any,
) -> Any:

Parameters:

ParameterTypeDefaultDescription
totype[BaseDBModel]requiredTarget model class referenced by this FK
on_deleteFKAction"RESTRICT"Action when referenced record is deleted
on_updateFKAction"RESTRICT"Action when referenced record's PK is updated
nullboolFalseWhether the FK field can be NULL
uniqueboolFalseWhether the FK must be unique (one-to-one)
related_namestr | NoneNoneName for reverse relationship (reserved)
db_columnstr | NoneNoneCustom column name; defaults to {field_name}_id
defaultAny...Default value; auto-set to None if null=True
**kwargsAnyAdditional arguments passed to Pydantic Field

Returns:

A Pydantic Field with foreign key metadata.

Raises:

Example:

from sqliter.model import BaseDBModel, ForeignKey


class Author(BaseDBModel):
    name: str


class Book(BaseDBModel):
    title: str
    author_id: int = ForeignKey(Author, on_delete="CASCADE")

ForeignKeyInfo

Dataclass holding metadata about a foreign key relationship. Created internally by ForeignKey() and stored in the field's json_schema_extra["foreign_key"].

@dataclass
class ForeignKeyInfo:
    to_model: type[BaseDBModel]
    on_delete: FKAction
    on_update: FKAction
    null: bool
    unique: bool
    related_name: str | None
    db_column: str | None

Fields:

FieldTypeDescription
to_modeltype[BaseDBModel]Target model class
on_deleteFKActionDelete action
on_updateFKActionUpdate action
nullboolWhether the FK is nullable
uniqueboolWhether the FK must be unique
related_namestr | NoneReverse relationship name
db_columnstr | NoneCustom column name

get_foreign_key_info()

Extract ForeignKeyInfo from a Pydantic FieldInfo object, if the field is a foreign key.

def get_foreign_key_info(
    field_info: FieldInfo,
) -> ForeignKeyInfo | None:

Parameters:

ParameterTypeDefaultDescription
field_infoFieldInforequiredThe Pydantic field info to examine

Returns:

ForeignKeyInfo | None -- The FK metadata if the field is a foreign key, None otherwise.

Example:

from sqliter.model.foreign_key import get_foreign_key_info

field_info = Book.model_fields["author_id"]
fk_info = get_foreign_key_info(field_info)
if fk_info:
    print(fk_info.to_model)   # <class 'Author'>
    print(fk_info.on_delete)  # "CASCADE"