SQLAlchemy:如何从多态子级中选择属性而不加入其父级

kel*_*ket 5 python sqlalchemy

给定一个多态类层次结构:

class A(Base):
    __tablename__ = 'a'
    a_id = Column('id', Integer, primary_key=True)
    type = Column(String(255), nullable=False)

    __mapper_args__ = {
        'polymorphic_identity': 'a',
        'polymorphic_on': type
    }


class B(A):
    __tablename__ = 'b'
    id = Column(Integer, primary_key=True)
    a_id = Column(Integer, ForeignKey(A.a_id))

    __mapper_args__ = {
        'polymorphic_identity': 'b',
    }
Run Code Online (Sandbox Code Playgroud)

我不想B被强迫加入反对A,如果我只检索从属性B,如:session.query(B.id).all()。此外,我注意到给定的第三个类型表A与 有关系B

class C(A):
    __tablename__ = 'c'
    id = Column(Integer, primary_key=True)
    a_id = Column(Integer, ForeignKey(A.a_id))
    b_id = Column(Integer, ForeignKey(B.id))
    b = relationship(B, foreign_keys=[b_id])
    __mapper_args__ = {
        'polymorphic_identity': 'c',
    }
Run Code Online (Sandbox Code Playgroud)

如果查询需要连接到该表C,例如:

session.query(B.id).join(C.b).filter(C.id == x).all() 
Run Code Online (Sandbox Code Playgroud)

查询将自动连接到C的基础父表和B的基础父表(这是A在不引用任何表A属性的单个查询中的两个连接),使查询不必要地冗长和复杂。

有没有什么方法可以配置 SQLAlchemy 仅在需要属性时才加入多态父表?我一直无法在文档中找到有关此用例的任何信息,但很难相信像 SQLAlchemy 这样灵活的库会以这种方式受到限制。