Repository navigation
v0.28.0
🔗 Explicit foreign keys: the key is a column you declare, and a relation is a typed view of it
A foreign key is now an ordinary field on your model. Before, ForeignKey() created an account_id column you never wrote, and the other model needed a BackRef() whose name had to match. Now you declare account_id yourself with Field(foreign_key=Account), and a relation is an optional attribute that names that column:
from ferro import Field, Forward, Model, Relation, Reverse
class Account(Model):
id: int | None = Field(default=None, primary_key=True)
name: str
class Note(Model):
id: int | None = Field(default=None, primary_key=True)
body: str
account_id: int = Field(foreign_key=Account, index=True)
reply_to_id: int | None = Field(default=None, foreign_key="Note", on_delete="SET NULL")
account: Relation[Account] = Forward("account_id")
reply_to: Relation["Note | None"] = Forward("reply_to_id")
replies: Relation[list["Note"]] = Reverse("reply_to_id")Note.account_id is the column the old form created, so the schema stays as it was: the same columns, the same fk_* constraints, the same join tables. What changes is that you can read the key, filter on it and give it options (index=, unique=, db_type=, renamed_from=) the way you do for any other field. A forward relation no longer needs its other side, so Account declares nothing here.
This is a breaking release. ForeignKey(), BackRef(), ManyToMany(related_name=...) and await note.account are refused by name, and each refusal points at the section of the upgrade guide that converts it.
The three relation forms
Forward("account_id")reads the row a key column on this model points at. Read it withawait note.account.load(), or asnote.accountafterinclude().Reverse("reply_to_id")reads the rows whose key column points back at this one, as a query you can filter and order.ManyToMany(through="tag_notes")names its join table, which Ferro still creates and owns. The other side isReverse("notes").
A refusal names its fix
A declaration Ferro cannot build is refused when the class is defined, with the line to write instead. A key column whose storage disagrees with the key it references is one:
class Ledger(Model):
id: int | None = Field(default=None, primary_key=True, db_type="bigint")
class Entry(Model):
id: int | None = Field(default=None, primary_key=True)
ledger_id: int = Field(foreign_key=Ledger) # TypeError: names db_type="bigint" to add
ledger: Relation[Ledger] = Forward("ledger_id")A relation that names a model which is never defined now raises a TypeError with the fix too, where it used to raise a bare RuntimeError (#962).
Upgrading
The upgrade guide has a conversion table with one row per old declaration, the converted models in both declaration styles, an acceptance check (ferro migrate check prints ok, or await ferro.migrate() returns no statements) and a prompt you can paste into a coding agent to do the conversion.
Six changes outside relations also reach code that runs today. The guide's Changes outside relations covers each one:
- Bytes over a text column are refused on Postgres. A
bytesfield whose live column isvarcharortextraises aDataErrorthat names the field and the fix, on every write and every fetch, before any statement is sent.0.27stored the hex text (#834, #963). - A JSON field loads as its declared type. A nested Pydantic model, a
setor alist[datetime]comes back as that type, where0.27gave you the decoder'sdict,listandstr(#832). - A fetched record lists its fields in declaration order, as a constructed one does.
0.27gave them alphabetically (#829). - Raw SQL binds a UTC time the way
save()stores it, ending inZ. On SQLite a rawWHERE created_at = ?now finds the rowsave()wrote. Rows that raw SQL wrote in0.27need a one-timeUPDATE t SET col = replace(col, '+00:00', 'Z')(#982). - A UTC offset with seconds is refused. A
datetimeortimewith an offset such as+05:30:15raisesValueErroron every write path, where0.27stored it up to a minute off. Convert it first withvalue.astimezone(timezone.utc)(#982). Model.all()sends the statement a query sends, ending inWHERE TRUE. This matters only to a test that matches logged SQL (#963).
Also in this release
- A model whose only column is an autoincrement primary key can be saved; Ferro writes
INSERT ... DEFAULT VALUES(#967). - A many-to-many join table types its key columns by the same rule as every other column, so a
Decimalordateprimary key no longer failscreate_tables()(#937). - Many-to-many
add()andremove()identify instances by primary key, and raise on an unsaved instance or one of the wrong model (#839). - A foreign key references the target's primary-key column, whatever it is named (#828).
- New guide page: Inspecting SQL, on the
ferro.sqllog and.sql()(#833).
Full design and discussion: #874, #917.
v0.28.0 (2026-11-17)
Bug Fixes
-
A foreign key references the target's primary-key column (#612) (#828,
2893467) -
A many-to-many's join table types its key column by a second rule, so a Decimal or date primary key fails create_tables() (#936) (#937,
fe1f147) -
A model with only an autoincrement primary key cannot be saved (#838) (#967,
45fbdcf) -
A relation naming an undefined model raises a RuntimeError with no fix (#945) (#962,
40cde0d) -
Detect a ForeignKey in a string annotation and under an outer Optional (#751) (#827,
de3ad4e) -
Hydrated instances list fields in declaration order (#754) (#829,
685a5df) -
JSON-family fields hydrate as their declared type (#737) (#832,
e1d49a4) -
Many-to-many add() and remove() identify instances by primary key (#830) (#839,
2c58a4d) -
Model.all() builds its own SELECT so it skips the storage check (#944) (#963,
3a47c8d) -
Raw SQL binds a UTC datetime as +00:00 where save() stores Z, so a raw SQLite query for a saved timestamp finds no row (#976) (#982,
c660e25) -
Refuse bytes against a text column on Postgres (#785) (#834,
eddd177) -
release: Re-lock uv.lock in the release commit (#931,
f5e497f)
Documentation
-
Bring AGENTS.md up to the contracts main already keeps (#942,
5a3ad06) -
Declare columns before relations in every model example (#986,
8de03e3) -
Make the upgrade guide ready for 0.28 (#965) (#966,
d9bb39f)
Features
Refactoring
-
Make a model's forward relation specs complete from class definition (#934) (#935,
6143aab) -
Move relation declaration reading behind relations (#932) (#933,
c3d015c)
Testing
-
Give the sibling-target models a primary key so main is green after #827 and #828 (#831,
cf1ee43) -
Remove 291 tests whose Keepers already catch the same break (#961,
5e5011d) -
Run test=pytest fences from any docs page (#835) (#840,
e4a87aa) -
Scope the carried-policy lookup to the test's own table (#836,
fa47257) -
Test model declaration through class definitions (#928) (#929,
f9bfe24)
Detailed Changes: v0.27.0...v0.28.0