嘗試使用Session.expunge處理每個節點(帶孩子)後清理會話。下面的示例代碼打印會話中的實例數量:
class Node(Base):
__tablename__ = 'node'
id = Column(Integer, primary_key=True)
parent_id = Column(Integer, ForeignKey('node.id'))
name = Column(String(50))
children = relationship("Node",
backref=backref("parent", remote_side=[id],)
)
def process_node(node, expunge=False, ident=1):
print "Node: ", "-" * ident, node, " --> ", len(session.identity_map)
for child in node.children:
process_node(child, expunge, ident + 4)
session.expunge(child)
roots = session.query(Node).filter(Node.parent == None)
for root in roots:
process_node(root, True)
來源
2012-05-25 15:00:45
van