Other answers using uselist=False
are correct, but in SQLAlchemy 2.0 relationship
is now smart enough to deduce it if your Mapped
annotation uses a non-collection type.
From the docs:
New in version 2.0: The relationship()
construct can derive the effective value of the relationship.uselist
parameter from a given Mapped
annotation.
Here is chadwick.boulay’s code modified for SqlAlchemy 2.0:
class Parent(Base):
__tablename__ = 'parent'
id: Mapped[int] = mapped_column(Integer(), primary_key=True)
child: Mapped["Child"] = relationship("Child", backref="parent")
class Child(Base):
__tablename__ = 'child'
id: Mapped[int] = mapped_column(Integer(), primary_key=True)
parent_id: Mapped[int] = mapped_column(Integer(), ForeignKey('parent.id'))
Notice how child
is annotated with Mapped["Child"]
, i.e. child
is one Child
. If you wanted to use a one-to-many relationship, you would annotate it as a list:
children: Mapped[List["Child"]] = relationship("Child", backref="parent")
uselist
keyword has no impact if the FK of the join is in the same class than the relationship definition. See the answer of chadwick.boulay for the correct solution. – Mir