我使用 sqlalchemy 并为两个一对多相关的表创建了类。并希望在其两个定义中都使用 column_property
来添加计算字段。
我可以在 Tbl1
的 column_property
中引用 Tbl2
,因为它是在 Tbl2
之前定义的,但我不能在 Tbl1
中这样做。>
有没有办法通过使用字符串表/列名称或使用字符串过滤来实现这一点,而不是通过类引用?
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),
))
)