If have following ORM setup in SQLAlchemy:
class Foo(Base):
id = Column(Integer, primary_key=True)
status = Column(String)
barId = Column(Integer, ForeignKey("bar.id"))
bar = relationship("Bar", lazy="joined")
class Bar(Base):
id = Column(Integer, primary_key=True)
So I would like to always have the associated Bar object available for each Foo object. I often detach the Foo objects from the session and continue using its values and Bar's values. From time to time I need to update Foo's status field. In that case I create a new session, add the foo object to the session and commit it. After the commit the Bar object associated with the Foo object is invalidated but not reloaded by the commit's implicit refresh of the Foo object. After detaching the Foo object again from the session, the Bar object is no longer usable. The only way I found to work around that is to explicitly eager load the bar object after committing foo.
Example work flow:
session = Session()
foo = session.query(Foo).get(id) <-- foo.bar is automatically eager loaded
session.close()
....
session = Session()
session.add(foo)
foo.status = 'done'
session.commit() <-- foo is commited and refreshed, foo.bar is not
session.refresh(foo) <-- same here, foo.bar is not loaded
#foo.bar <-- only explicit eager loading foo.bar here works
session.close()
....
foo.bar <-- error if not explicitly eager loaded
I would like to use this setup for a few of those small Bar like objects. Requiring me to remember to always explicitly reload the foo.bar object is error prone. So my question is: can I eager load foo.bar in all situations, be it a query(), a commit() (implicit refresh) or an (explicit) refresh()?