一尘不染

sqlalchemy多态多对多

python

我正在寻找以下列方式属于父类的对象的列表:

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的“父”类(而不是相反),但是我一生都无法解决如何将其逆转为一对多,然后添加双向关系以使其变为多对多。

谁能帮我这个忙吗?


阅读 168

收藏
2021-01-20

共1个答案

一尘不染

这有点痛苦,并且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
2021-01-20