我希望以下列方式获得属于父类的对象列表:
class A(object):
__tablename__ = 'a'
id = Column(Integer, primary_key=True)
collection = relationship(.....) # contains an ordered list of [B, C, B, B, C, C, C, B, C, C, ...];
class B(object):
__tablename__ = 'b'
id = Column(Integer, primary_key=True)
class C(object):
__tablename__ = 'c'
id = Column(Integer, primary_key=True)
SQLAlchemy examples文件夹有一个简单的多对一,在我的例子中,类B和C是A的“父”类(而不是相反),但我不能为我的生活做出努力如何将其转换为一对多,然后添加双向关系,使其成为多对多关系.
任何人都可以帮我解决这个问题吗?
解决方法:
它有点痛苦,而AbstractConcreteBase显然需要更多的润色,但它是这样的:
from sqlalchemy import *
from sqlalchemy.orm import *
from sqlalchemy.ext.declarative import declarative_base, AbstractConcreteBase
Base = declarative_base()
class A(Base):
__tablename__ = 'a'
id = Column(Integer, primary_key=True)
class BC(AbstractConcreteBase, Base):
pass
class B(BC):
__tablename__ = 'b'
id = Column(Integer, primary_key=True)
a_id = Column(Integer, ForeignKey('a.id'))
__mapper_args__ = {
"polymorphic_identity": "b",
"concrete": True
}
class C(BC):
__tablename__ = 'c'
id = Column(Integer, primary_key=True)
a_id = Column(Integer, ForeignKey('a.id'))
__mapper_args__ = {
"polymorphic_identity": "c",
"concrete": True
}
configure_mappers()
A.collection = relationship(BC, primaryjoin=BC.a_id == A.id)
engine = create_engine("sqlite://", echo=True)
Base.metadata.create_all(engine)
sess = Session(engine)
sess.add_all([
A(collection=[
B(),
C(),
C()
]),
A(collection=[
B(),
B()
])
])
sess.commit()
for a in sess.query(A):
for bc in a.collection:
print a, bc