使用生成选择选择特定列
我正在学习SQLAlchemy,并且在看表达式语言教程。我特别喜欢生成查询,因为我可以使用表的反射功能,然后用表类的方法轻松查询表。这就是我现在正在做的事情。
from sqlalchemy import Table, create_engine, MetaData
engine = create_engine('mysql://...')
meta.bind = engine
table = Table('footable', meta, autoload=True)
result = table.select().where(...).execute()
我之前写过很多查询,通常我只选择我需要的特定列,而不是选择所有列。有没有办法在我的SQLAlchemy查询中指定返回哪些列呢?
1 个回答
1
在文档中可以查看更多关于 select() 的内容,特别是前两个参数的部分。
不过,接下来提供的内容应该是你工作的正确方向:
from sqlalchemy.sql import select, and_, or_, not_
# ...
query = select(# what to select (tables or columns)
[table.c.column1, table.c.column2],
# filters (use any expression using and_, or_, not_...
and_(table.c.column1.like("j%")),
)
result = query.execute()