假设我正在使用如下的声明性对象:
class MyObject(DeclarativeBase):
...
other_object_id = Column(Integer, ForeignKey('other_object.id'))
other_object = relationship("OtherObject")
...
假设我想要一个方便方法set_other_object_value
,它会修改other_object.value
,创建 OtherObject
的实例并将其添加到会话中,如有必要:
def set_other_object_value(self, value):
if self.other_object is None:
<create instance of OtherObject and associate with the session>
self.other_object.value = value
问题是:我如何创建OtherObject
并将其与会话相关联?一个可能等同的问题:是否可以访问Session
的实例,MyObject
的实例中添加了MyObject
?
答案 0 :(得分:2)
from sqlalchemy.orm.session import object_session
# ...
def set_other_object_value(self, value):
if self.other_object is None:
value = OtherObject(...)
self.other_object.value = value
object_session(self).add(value)
但是,如果您已正确设置了关系,则无需将新value
添加到会话中,因为sqlalchemy
会将其弄清楚并将其保存到{{1}上的数据库中无论如何。