2010-11-19 31 views
1

Voici ma requête SQL:Comment puis-je exprimer cette requête dans 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 

J'ai des entités ORM pour survey_spec, survey_installation_history et users et survey_spec.installations est une relation à l'aide survey_installation_historysurvey_spec_id comme la clé.

Répondre

1

Avez-vous l'exemple de sortie de ce que vous avez déjà? à savoir la sortie de:

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

Si vous voulez juste charger vos entités, vous pouvez contourner la génération SQL et la charge de votre donnée literal SQL, quelque chose le long des lignes de:

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