Field, Forward, Reverse, ManyToMany and Relation¶
A relationship starts from a foreign-key column, declared as team_id: int = Field(foreign_key=Team); Field is documented with the other field options. Forward("team_id") reads the related instance through that column, Reverse("team_id") queries the rows of another model whose column points back, and ManyToMany(through=...) links two models through a join table Ferro creates. Every relation is annotated Relation. See the Relationships guide for usage patterns.
ManyToMany
¶
ManyToMany(*, through: str | None = None, renamed_from: str | None = None, reverse_index: bool = True, **unknown: Any) -> Any
Declare a many-to-many relation, assigned as the field's default.
Annotate the field Relation[list[Target]] and name its join table.
Ferro creates that table, with one <table>_id column per model, a
unique index over the pair and an index for reads from the other side.
The target reads the relation back through a
Reverse naming this field, which it may leave out.
See Many-to-many.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
through
|
str | None
|
The join table's name. Required: a model with no
|
None
|
renamed_from
|
str | None
|
The join table's previous name, so that
|
None
|
reverse_index
|
bool
|
Add an index on the join table's |
True
|
Returns:
| Type | Description |
|---|---|
Any
|
The field's metadata, as |
Raises:
| Type | Description |
|---|---|
TypeError
|
Any other keyword, such as a column option (a
many-to-many adds no column) or |
Examples:
from ferro import Field, ManyToMany, Model, Relation, Reverse, create_tables
class Tag(Model):
id: int | None = Field(default=None, primary_key=True)
label: str
articles: Relation[list["Article"]] = Reverse("tags")
class Article(Model):
id: int | None = Field(default=None, primary_key=True)
title: str
tags: Relation[list[Tag]] = ManyToMany(through="article_tags")
await create_tables()
history = await Tag.create(label="history")
article = await Article.create(title="Babbage's engines")
await article.tags.add(history)
assert [tag.label for tag in await article.tags.all()] == ["history"]
assert [found.title for found in await history.articles.all()] == [
"Babbage's engines"
]
- Guide Relationships
- Reference Python API Field, Forward, Reverse, ManyToMany and Relation
Forward
¶
Declare a forward relation over a foreign-key column of this model.
Assign it to a field annotated Relation[Target], or
Relation[Target | None] when the column allows None. On an
instance the relation reads as the instance the column points at: the
complete one an include() or .load() filled, or the session's
instance for that key, or an unloaded instance holding only the key,
which .load() fills in place. Assigning an instance to it sets the
column. It adds no
column; the foreign-key column is the field declared with
Field(foreign_key=Target). See
Loaded relations.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
column
|
str
|
The name of the foreign-key column on this model. |
required |
Returns:
| Type | Description |
|---|---|
Any
|
The field's metadata, as |
Raises:
| Type | Description |
|---|---|
TypeError
|
|
Examples:
from ferro import Field, Forward, Model, Relation, create_tables
class Shelf(Model):
id: int | None = Field(default=None, primary_key=True)
label: str
class Book(Model):
id: int | None = Field(default=None, primary_key=True)
title: str
shelf_id: int = Field(foreign_key=Shelf, index=True)
shelf: Relation[Shelf] = Forward("shelf_id")
await create_tables()
history = await Shelf.create(label="History")
await Book.create(title="SPQR", shelf_id=history.id)
book = await Book.select().include(lambda book: book.shelf).first()
assert book.shelf.label == "History"
- Guide Relationships One-to-many Loaded relations
- Reference Python API Field, Forward, Reverse, ManyToMany and Relation
Reverse
¶
Declare a reverse relation over a foreign-key column of another model.
Assign it to a field annotated Relation[list[Other]], where Other
declares the foreign-key column with Field(foreign_key=ThisModel). On
an instance the relation is a query over the rows whose column holds
this instance's primary key. Neither side names the other: a
Forward needs no Reverse. See
Relationships.
attribute may also name a ManyToMany on the
other model, and the relation reads the rows its join table links.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
attribute
|
str
|
The name of the foreign-key column, or of the many-to-many, on the other model. |
required |
Returns:
| Type | Description |
|---|---|
Any
|
The field's metadata, as |
Raises:
| Type | Description |
|---|---|
TypeError
|
|
Examples:
from ferro import Field, Model, Relation, Reverse, create_tables
class Shelf(Model):
id: int | None = Field(default=None, primary_key=True)
label: str
books: Relation[list["Book"]] = Reverse("shelf_id")
class Book(Model):
id: int | None = Field(default=None, primary_key=True)
title: str
shelf_id: int = Field(foreign_key=Shelf)
await create_tables()
history = await Shelf.create(label="History")
await Book.create(title="SPQR", shelf_id=history.id)
titles = [book.title for book in await history.books.all()]
assert titles == ["SPQR"]
- Guide Relationships One-to-many Loaded relations
- Reference Python API Field, Forward, Reverse, ManyToMany and Relation
Relation
¶
Bases: Query[T]
The annotation of every relation: forward, reverse and many-to-many.
A forward relation (Forward) is annotated
Relation[Target], or Relation[Target | None] when its foreign-key
column allows None. On an instance it reads as the instance its column
points at: the complete one an include() or .load() filled, or the
session's instance for that key, or an unloaded instance holding only the
key, which .load() fills in place. Assigning an instance to it sets the
column.
A reverse (Reverse) or many-to-many
(ManyToMany) relation is annotated
Relation[list[Target]]. On an instance it is this query over the
related rows: await .all() to read them, or chain where(),
order_by() and the other query methods first. See
Relationships.
Examples:
post = await Post.where(lambda post: post.views > 1000).first()
ada = await post.author.load()
assert ada.name == "Ada Lovelace"
posts = await ada.posts.all()
assert [post.title for post in posts] == ["Notes on the Analytical Engine"]
- Guide Relationships One-to-many Loaded relations
- Reference Python API Field, Forward, Reverse, ManyToMany and Relation
Methods:
| Name | Description |
|---|---|
add |
Link instances to the owner of a many-to-many relation. |
remove |
Unlink instances from the owner of a many-to-many relation. |
clear |
Unlink every instance from the owner of a many-to-many relation. |
all |
Load every related record. |
first |
Load the first related record, or |
add
async
¶
add(*instances: Any) -> None
Link instances to the owner of a many-to-many relation.
Call it on the relation, as in await post.tags.add(history, science).
See Many-to-many.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
*instances
|
Any
|
The related instances to link. Each is identified by its primary key and must be saved first. |
()
|
Raises:
| Type | Description |
|---|---|
RuntimeError
|
The query is not a many-to-many relation. |
TypeError
|
An instance is not of the related model. |
ValueError
|
An instance or the owner has no primary key yet. Save it first. |
remove
async
¶
remove(*instances: Any) -> None
Unlink instances from the owner of a many-to-many relation.
Call it on the relation, as in await post.tags.remove(history). The
instances' rows stay; only the links go.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
*instances
|
Any
|
The related instances to unlink. Each is identified by its primary key and must be saved first. |
()
|
Raises:
| Type | Description |
|---|---|
RuntimeError
|
The query is not a many-to-many relation. |
TypeError
|
An instance is not of the related model. |
ValueError
|
An instance or the owner has no primary key yet. Save it first. |
clear
async
¶
Unlink every instance from the owner of a many-to-many relation.
Call it on the relation, as in await post.tags.clear(). The related
rows stay; only the links go.
Raises:
| Type | Description |
|---|---|
RuntimeError
|
The query is not a many-to-many relation. |
ValueError
|
The owner has no primary key yet. Save it first. |
all
async
¶
Load every related record.
Returns:
| Type | Description |
|---|---|
list
|
The related instances, in the query's order. |
Examples: