SELECT * in SQLAlchemy?

2020-06-30 11:56发布

Is it possible to do SELECT * in SQLAlchemy?

Specifically, SELECT * WHERE foo=1?

8条回答
冷血范
2楼-- · 2020-06-30 12:05

If you don't list any columns, you get all of them.

query = users.select()
query = query.where(users.c.name=='jack')
result = conn.execute(query)
for row in result:
    print row

Should work.

查看更多
做个烂人
3楼-- · 2020-06-30 12:11

Turns out you can do:

sa.select('*', ...)
查看更多
Animai°情兽
4楼-- · 2020-06-30 12:13

You can always use a raw SQL too:

str_sql = sql.text("YOUR STRING SQL")
#if you have some args:
args = {
    'myarg1': yourarg1
    'myarg2': yourarg2}
#then call the execute method from your connection
results = conn.execute(str_sql,args).fetchall()
查看更多
淡お忘
5楼-- · 2020-06-30 12:23

The following selection works for me in the core expression language (returning a RowProxy object):

foo_col = sqlalchemy.sql.column('foo')
s = sqlalchemy.sql.select(['*']).where(foo_col == 1)
查看更多
Evening l夕情丶
6楼-- · 2020-06-30 12:24

For joins if columns are not defined manually, only columns of target table are returned. To get all columns for joins(User table joined with Group Table:

sql = User.select(from_obj(Group, User.c.group_id == Group.c.id))
# Add all coumns of Group table to select
sql = sql.column(Group)
session.connection().execute(sql)
查看更多
女痞
7楼-- · 2020-06-30 12:28

Where Bar is the class mapped to your table and session is your sa session:

bars = session.query(Bar).filter(Bar.foo == 1)
查看更多
登录 后发表回答