我有像这样的sqlalchemy关系(为简单而修剪):
class Parent(Base):
__tablename__ = 'Parent'
name = Column(String,nullable=False)
def __init__(self,name)
self.name = name
class Child(Base):
__tablename__ = 'Child'
name = Column(String,nullable=False)
parent = relationship(Parent,backref=backref('children')
def __init__(self,name,parent)
self.name = name
self.parent = parent
在我的对象工作的同时:
parent = Parent("my parent")
db_session.add(parent) # must be done for other reasons not relevant to the issue.
child = Child("my child",parent)
到现在为止还挺好.
但是在我执行以下操作之前,我得到了一个DB flush:
children = parent.children # using the backref causes a flush
通过改变我定义backref /关系的方式可以避免这种情况吗?
最佳答案
使用Session.no_autoflush上下文管理器应该以安全的方式实现您想要的:
with session.no_autoflush:
parent = Parent("my parent")
db_session.add(parent)
child = Child("my child",parent)