2017年12月6日 星期三

[ Python 常見問題 ] Sqlalchemy in clause

Source From Here 
Question 
I'm trying to do this query in SQLAlchemy
SELECT id, name FROM user WHERE id in (123,456)

I would like to bind the list [123,456] at execution time. 

How-To 
How about session.query(MyUserClass).filter(MyUserClass.id.in_((123,456))).all() ? 
  1. session.execute(  
  2.     select(  
  3.         [MyUserTable.c.id, MyUserTable.c.name],   
  4.         MyUserTable.c.id.in_((123456))  
  5.     )  
  6. ).fetchall()  
select() takes two parameters, the first one is a list of fields to retrieve, the second one is the where condition. You can access all fields on a table object via the c (or columns) property.

沒有留言:

張貼留言

[ Python 文章收集 ] SQLAlchemy quick start with PostgreSQL

Source From   Here   Preface   This is a quick tutorial for getting started with   SQLAlchemy Core API .   Prerequisites   In this quick st...