当我的 python 应用程序启动时,我想从中加载所有数据in.db
并将其放入out.db
(然后可能在 中进行更改out.db
)。我使用session.merge(loaded_object)
,但问题是它不保存相关对象。
我的数据是简单的 Person 对象,它们之间有明显的父子关系(多对多):
from sqlalchemy import create_engine, Column, String, Integer, ForeignKey
from sqlalchemy.orm import sessionmaker, relationship, backref
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
class Person(Base):
__tablename__ = "people"
id = Column(Integer, primary_key=True)
name = Column(String)
def __init__(self, name):
self.name = name
def add_kid(self, kid):
Edge(kid=kid, parent=self)
return self
def get_kids(self):
return [edge.kid for edge in self.kid_edges]
def add_parent(self, parent):
Edge(kid=self, parent=parent)
return self
def get_parents(self):
return [edge.parent for edge in self.parent_edges]
def __repr__(self):
return "<Person(id={id}, name={name})>".format(id=str(self.id),
name=self.name)
class Edge(Base):
__tablename__ = "edges"
id = Column(Integer, primary_key=True)
kid_id = Column(Integer, ForeignKey("people.id"))
parent_id = Column(Integer, ForeignKey("people.id"))
kid = relationship("Person", primaryjoin="Edge.kid_id==Person.id",
backref=backref("parent_edges",
collection_class=set))
parent = relationship("Person", primaryjoin="Edge.parent_id==Person.id",
backref=backref("kid_edges",
collection_class=set))
def __init__(self, kid, parent):
self.kid = kid
self.parent = parent
我通过以下方式初始化会话:
db_in_engine = create_engine("sqlite:///in.db", echo=True)
db_in_session_factory = sessionmaker(bind=db_in_engine)
db_in_session = db_in_session_factory()
db_out_engine = create_engine("sqlite:///out.db", echo=True)
db_out_session_factory = sessionmaker(bind=db_out_engine)
db_out_session = db_out_session_factory()
Base.metadata.create_all(db_out_engine)
问题是当我合并一个人时,孩子们没有合并:
people = db_in_session.query(Person).all()
db_out_session.merge(people[0])
db_out_session.commit() # related Edges, kids and parents of people[0] are not saved
我尝试将 cascade="merge" 添加到关系和反向引用中,但这不起作用。有什么办法可以强迫它拯救所有人[0]的孩子/父母和相关的边缘?