2010-11-19 3 views
1

Вот мой SQL-запрос:Как я могу выразить этот запрос в ORM sqlalchemy?

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_spec, survey_installation_history и users и survey_spec.installations это отношение к survey_installation_history с помощью survey_spec_id в качестве ключа.

ответ

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() 
Смежные вопросы