carl carl - 7 months ago 30
Python Question

sqlalchemy: one-to-one relationship with declarative

What is the best way to create a one-to-one relationship in SQLAlchemy using declarative?

I have two tables,

foo
and
bar
, and I want
foo.bar_id
to link to
bar
. The catch is that this is a one-way one-to-one relationship.
bar
must not know anything about
foo
. For every foo, there will be one and only one
bar
.

Ideally, after selecting a foo, I could do something like this:

myfoo.bar.whatever = 5


What's the best way to accomplish this using declarative?

Answer Source

If you want a true one-to-one relationship, you also have to use the "uselist=False" in your relationship definition.

bar_id = Column(Integer, ForeignKey(Bar.id))
bar = relationship(Bar, uselist=False)