2010-11-19 57 views
1

這裏是我的SQL查詢:如何在sqlalchemy ORM中表示此查詢?

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 

我ORM實體survey_specsurvey_installation_historyusers,並survey_spec.installations是使用survey_spec_id爲重點,以survey_installation_history的關係。

回答

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()