2013-04-20 51 views
0

假设我使用的是声明对象如下所示: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的实例中添加的?

回答

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将数字出来,并将其保存到数据库上commit无论如何。