# 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](<https://ferro-orm.x54.sh/guide/relationships/index.md>) for usage patterns.

## ManyToMany

```python
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](<https://ferro-orm.x54.sh/guide/relationships/#many-to-many>).

Parameters:

| Name | Type | Description | Default |
| --- | --- | --- | --- |
| `through` | `str \| None` | The join table's name. Required: a model with no `through=`, or one that is not a table name, is refused when its class is defined, naming the table to write. | `None` |
| `renamed_from` | `str \| None` | The join table's previous name, so that `ferro migrate new` and auto-migrate rename the table and keep its rows. See [Renaming a join table](<https://ferro-orm.x54.sh/guide/schema/renames-and-retirements/#renaming-a-join-table>). | `None` |
| `reverse_index` | `bool` | Add an index on the join table's `(target, source)` columns for queries from the other side. Defaults to `True`; turn it off for a write-heavy join table. | `True` |

Returns:

| Type | Description |
| --- | --- |
| `Any` | The field's metadata, as `Field` returns it. |

Raises:

| Type | Description |
| --- | --- |
| `TypeError` | Any other keyword, such as a column option (a many-to-many adds no column) or `related_name`, which the other model's `Reverse` replaces. |

Examples:

```python
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"
]
```

## Forward

```python
Forward(column: str) -> Any
```

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](<https://ferro-orm.x54.sh/guide/relationships/#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 `Field` returns it. |

Raises:

| Type | Description |
| --- | --- |
| `TypeError` | `column` is not a non-empty string. |

Examples:

```python
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"
```

## Reverse

```python
Reverse(attribute: str) -> Any
```

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](<https://ferro-orm.x54.sh/guide/relationships/index.md>).

`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 `Field` returns it. |

Raises:

| Type | Description |
| --- | --- |
| `TypeError` | `attribute` is not a non-empty string. |

Examples:

```python
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"]
```

## Relation

```python
Relation(model_cls: Type[T], using: str | None = None, session: Any | None = None)
```

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](<https://ferro-orm.x54.sh/guide/relationships/index.md>).

Examples:

```python
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"]
```

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 `None` when there is none. |

### add

```python
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](<https://ferro-orm.x54.sh/guide/relationships/#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

```python
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

```python
clear() -> None
```

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

```python
all()
```

Load every related record.

Returns:

| Type | Description |
| --- | --- |
| `list` | The related instances, in the query's order. |

Examples:

```python
grace = await Author.get(2)
posts = await grace.posts.all()
assert [post.title for post in posts] == ["The Education of a Computer"]
```

### first

```python
first()
```

Load the first related record, or `None` when there is none.

Returns:

| Type | Description |
| --- | --- |
| `Any` | The first related instance in the query's order, or `None`. |

Examples:

```python
ada = await Author.get(1)
post = await ada.posts.order_by(lambda post: post.id).first()
assert post.title == "Notes on the Analytical Engine"
```
