Python 过滤sqlalchemy中一对多集合的最新记录
我有以下sqlalchemy模型Python 过滤sqlalchemy中一对多集合的最新记录,python,join,sqlalchemy,Python,Join,Sqlalchemy,我有以下sqlalchemy模型 class Alert(Base): __tablename__ = 'alerts' id = Column(Integer, primary_key=True) alert_text = Column(Text) @hybrid_property def latest_state(self): if self.state_changes: return self.stat
class Alert(Base):
__tablename__ = 'alerts'
id = Column(Integer, primary_key=True)
alert_text = Column(Text)
@hybrid_property
def latest_state(self):
if self.state_changes:
return self.state_changes[-1]
return self.state_changes
class AlertStateChange(Base):
__tablename__ = 'alert_state_change'
__table_args__ = (
PrimaryKeyConstraint('id', name='pk_alert_state_change'),
)
id = Column(Integer)
reason_id = Column(Integer, ForeignKey('reasons.id'))
alert_id = Column(Integer, ForeignKey(Alert.id))
reason = relationship('Reason', backref='state_changes')
alert = relationship(Alert, backref='state_changes')
status = Column(Text)
date = Column(DateTime)
class Reason(Base):
__tablename__ = 'reasons'
__table_args__ = (
PrimaryKeyConstraint('id', name='pk_reason'),
)
id = Column(Integer)
reason_text = Column(Text)
因此,警报的状态基本上是根据原因编辑的。当一个状态改变时,用户也会输入一条评论,并且关于谁发布了改变的信息也会被保留,但是为了简单起见,我已经排除了这两个字段。状态可以是打开
或关闭
,当用户打开警报时,不需要任何原因,因此原因id可以为空
我希望能够筛选当前已关闭且带有特定原因文本但找不到正确连接的警报
我从这个开始
session.query(Alert).join(AlertStateChange).join(Reason).filter(Reason.reason_text=='wanted reason)
但这会给我带来所有的警告,过去或现在的某个时间都是以“想要的理由”关闭的。如何仅使用当前状态(即每个警报的最新记录)进行筛选
q=…筛选(Reason.Reason\u text='wanted Reason')
然后q.filter(AlertStateChange.state='somestate')。all()
?这不会带来所有警报,这些警报在某些时候的状态为“somestate”,但不一定是其最新状态吗?如何定义laststate?时间还是时间?您可以再次筛选该查询,以确定您想要的状态。Test status是发生的最后一次状态更改,因此是每个查询的最新记录alert@Apostolos你有没有找到一个巧妙的解决办法?