如何在sqlalchemy ORM中表达此查询?

时间:2010-11-19 19:52:56

标签: python sql sqlalchemy

这是我的SQL查询:

select survey_spec.survey_spec_id, cr.login as created_by, installed_at, req.login as requested_by, role
from survey_spec
        join (select survey_spec_id, role, max(installed_at) as installed_at from survey_installation_history group by 1, 2) latest using (survey_spec_id)
        left join survey_installation_history using (survey_spec_id, role, installed_at)
        left join users cr on created_by = cr.user_id
        left join users req on requested_by = req.user_id
where survey_id = :survey_id
order by created_at desc, installed_at desc

我有survey_specsurvey_installation_historyusers的ORM实体,survey_spec.installationssurvey_installation_history的关系使用survey_spec_id作为键。

1 个答案:

答案 0 :(得分:1)

你有迄今为止所得到的示例输出吗?即输出:

print survey_spec.query.filter(survey_spec.survey_id==survey_id).options(
         eagerload(...))

如果您只想加载实体,可以绕过SQL生成并从给定的literal SQL加载,这类似于:

session.query(survey_spec).from_statement("""select survey_spec.survey_spec_id, cr.login as created_by, installed_at, req.login as requested_by, role
from survey_spec
 join (select survey_spec_id, role, max(installed_at) as installed_at from survey_installation_history group by 1, 2) latest using (survey_spec_id)
 left join survey_installation_history using (survey_spec_id, role, installed_at)
 left join users cr on created_by = cr.user_id
 left join users req on requested_by = req.user_id
where survey_id = :survey_id
order by created_at desc, installed_at desc""").params(survey_id=survey_id).all()