SqlAlchemy:从对象引用绑定会话?

时间:2013-04-20 16:18:07

标签: python sqlalchemy

假设我正在使用如下的声明性对象:

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

1 个答案:

答案 0 :(得分:2)

使用object_session

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}上的数据库中无论如何。

相关问题