Skip to content

Relationships

Declare related objects with Relationship(...) and load them with db.related(). Relationship fields are never persisted — only the foreign-key column is stored.

relationships

Relationship declarations.

Relationships are declared as annotated Pydantic-style fields using :class:Relationship as the default marker::

class Post(Model):
    author_id: int = Field(foreign_key="users.id")
    author: User | None = Relationship(foreign_key="author_id")

During model construction TinyStore detects these marker fields, records the relationship metadata, and replaces the field's default with None so that Pydantic sees a normal optional field. Relationship fields are never persisted to disk; related objects are loaded explicitly via db.related(instance, name).

Relationship dataclass

Relationship(
    foreign_key: str,
    to: Any = None,
    cardinality: str = CARDINALITY_MANY,
)

Declarative marker used as the default value of a relationship field.

to may be omitted when the relationship target can be inferred from the field's type annotation (resolved after all models are registered).

RelationshipMetadata dataclass

RelationshipMetadata(
    name: str,
    foreign_key: str,
    to_qualname: str,
    cardinality: str = CARDINALITY_MANY,
)

Resolved relationship metadata, stored on the model schema.