1

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

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并将其与会话关联?一个可能等效的问题:是否可以访问从 的实例中添加的 aSessionMyObject实例MyObject

4

1 回答 1

4

使用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都会弄清楚并将其保存到您的数据库中。commit

于 2013-04-20T20:51:05.633 回答