如何使用两个相关的对象属性获取最新结果

时间:2019-03-27 22:26:47

标签: python sql sqlalchemy

使用SQLAlchemy,我具有以下模型构造:

Category
    - slug as String (unique)
    ...

Sample
    - label
    ...

Result
    - sample_id (relation)
    ...

Specs
    - result_id (relation)
    - category_id (relation)
    - version as Integer
    ...

使用SQLAlchemy filter query by related object中的说明和python for循环,我能够检索所有样本的最新结果:

def get_latest_results(sample):
    subq = db.session.query(Specs.category_id, func.max(Specs.version).label('latest_version')) \
        .filter(Specs.result.any(sample=sample)) \
        .group_by(Specs.category_id).subquery('t2')

    query = db.session.query(Result).join(
        subq,
        and_(
            Result.specs.has(category_id=subq.c.category_id),
            Result.specs.has(version=subq.c.latest_version),
            Result.sample == sample,
        )
    ).all()
    return query


for sample in Sample.query.all():
    print(get_latest_results(sample))

现在,我正在尝试创建一个可在单一结构中完成所有工作的sqlalchemy查询。

到目前为止,每次尝试都会导致结果丢失或出现多余的意外情况……

输入数据如下:

Sample-1 Result-1 Specs-1-version-1 Category A
Sample-1 Result-2 Specs-2-version-2 Category A
Sample-1 Result-3 Specs-3-version-1 Category B
Sample-2 Result-4 Specs-4-version-1 Category A
Sample-2 Result-5 Specs-5-version-1 Category B

所需的输出(实际上,我想要Result对象,在此显示所有相关数据以确保完整性)

Sample-1 Result-2 Specs-2-version-2 Category A
Sample-1 Result-3 Specs-3-version-1 Category B
Sample-2 Result-4 Specs-4-version-1 Category A
Sample-2 Result-5 Specs-5-version-1 Category B

关于如何构建此查询集的任何想法?

0 个答案:

没有答案