如何在 flask SQL alchemy 中两次加入后进行过滤

How to filter after two joins in flask SQL alchemy

我有以下 3 个 tables:

class Sample(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    ...
    all_prosampairs = db.relationship('Prosampair', order_by="Prosampair.order", backref='modifies_sample', lazy=True, cascade="all, delete", passive_deletes=True)

class Process(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    date = db.Column(db.DateTime)
    ...
    all_prosampairs = db.relationship('Prosampair', backref='in_process', lazy=True, cascade="all, delete", passive_deletes=True)

class Prosampair(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    order = db.Column(db.Integer, nullable=False)
    ...
    process_id = db.Column(db.Integer, db.ForeignKey('process.id', ondelete="CASCADE"), nullable=False)
    sample_id = db.Column(db.Integer, db.ForeignKey('sample.id', ondelete="CASCADE"), nullable=False)

每个样本都有它经历的一系列过程,我需要得到一个 table,其中包括 Sample.id 和它遇到过程的最新日期,以便我可以过滤这个日期。

Something like this

到目前为止我尝试的是查看这个和类似的解决方案:

https://blog.miguelgrinberg.com/post/nested-queries-with-sqlalchemy-orm

但我不太明白如何处理我的第三种联想table。

 subqjoin1 = db.session.query(Sample).join(Prosampair).join(Process).subquery()
 subqjoin2 = db.session.query(subqjoin1, db.func.max(Process.date).label('latest_process')).group_by(Sample.id).subquery()
 result = db.session.query(subqjoin2).filter( subqjoin2.c.latest_process <= value ).all()

我得到了

的变体
sqlalchemy.exc.OperationalError: (sqlite3.OperationalError) no such column: sample.id

恐怕我不太了解如何访问我想要的参数。两个子查询可能是多余的,但我很难找到更好的方法

确保引用 .c 的子查询中的列,例如 subq.c.latest_process

with Session(engine) as session:
    latest_subq = session.query(
        Sample.id.label("sample_id"),
        func.max(Process.date).label("latest_process")
    ).outerjoin(
        Prosampair, Sample.id == Prosampair.sample_id
    ).outerjoin(
        Process, Prosampair.process_id == Process.id
    ).group_by(
        Sample.id
    ).subquery()

    q = session.query(Sample, latest_subq.c.latest_process).join(latest_subq, Sample.id == latest_subq.c.sample_id).order_by(latest_subq.c.latest_process)

    for sample, latest_process in q.all():
        print (sample.id, latest_process)