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

KT.*_*KT. 1 python sqlalchemy

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

class MyObject(DeclarativeBase):
   ...
   other_object_id = Column(Integer, ForeignKey('other_object.id'))
   other_object = relationship("OtherObject")
   ...
Run Code Online (Sandbox Code Playgroud)

假设我想要一个方便的方法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
Run Code Online (Sandbox Code Playgroud)

问题是:如何创建OtherObject并将其与会话关联?一个可能等效的问题:是否可以访问从 a 的Session实例MyObject中添加到的a 的实例MyObject

van*_*van 5

使用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)
Run Code Online (Sandbox Code Playgroud)

但是,如果您正确设置了关系,则无需将新内容添加value到会话中,因为无论如何sqlalchemy都会弄清楚并将其保存到数据库中commit