首页 > 解决方案 > Use strings in column_property queries

问题描述

I use sqlalchemy and have classes for two tables that are one-to-many related. And want to use column_property in both of their definitions to add calculated fields.

I can reference Tbl1 in column_property of Tbl2 because it is defined before Tbl2, but I can't do it in Tbl1.

It there any way to achieve this with using string table/column names or filtering using strings, rather than referring by class?

class Tbl1(Base):
    __tablename__ = 'tbl1'

    handle = Column(Integer, primary_key=True)
    name = Column(String)
    verified = Column(Boolean)

    published = column_property(
        exists()
        .where(and_(
            Tbl2.tbl1_handle == handle,  # <- At this point Tbl2 is not defined yet
            Tbl2.published.is_(True),    
        ))
    )


class Tbl2(Base):
    __tablename__ = 'tbl2'

    handle = Column(Integer, primary_key=True)
    name = Column(String)
    published = Column(Boolean)

    tbl1_handle = Column('tbl1', ForeignKey('tbl1.handle'))
    tbl1 = relationship('Tbl1', backref='tbl2s')

    verified = column_property(
        exists()
        .where(and_(
            Tbl1.handle == tbl1_handle,
            Tbl1.verified.is_(True),
        ))
    )

标签: pythonsqlalchemy

解决方案


推荐阅读