I want to write a query where I can dynamically pass various restrictions to SQLA Core. For example, I want to be able to specify on a SELECT
query WHERE
You can build your query dynamically without any problem. For instance, you can do:
query = select([table])
for key, value in params.iteritems():
query = query.where(table.columns[key] == value)
print conn.execute(query).fetchall()
where params
is just a dictionary of restrictions such as {'column': 'value'}
. This will produce a query in which all the where clauses are chained with AND. Of course, if you need more complex where clauses the construction of the query can be a bit more difficult.
A working example:
from sqlalchemy import select
from sqlalchemy import create_engine
from sqlalchemy import Column, String, Integer
from sqlalchemy.schema import MetaData, Table
# create engine and connection
DB_URI = "mysql+mysqldb://username:password@127.0.0.1:3306/database?charset=utf8mb4"
engine = create_engine(DB_URI, convert_unicode=True, echo=False)
conn = engine.connect()
# create table
metadata = MetaData()
pieces_table = Table('pieces', metadata,
Column('id', Integer, primary_key=True),
Column('size', String(60)),
Column('color', String(60)),
)
metadata.create_all(engine)
# insert data
conn.execute(pieces_table.insert(), [
{'size': 'small', 'color': 'blue'},
{'size': 'large', 'color': 'blue'},
{'size': 'small', 'color': 'red'},
])
# query data
def build_query(table, params):
query = select([table])
for key, value in params.iteritems():
query = query.where(table.columns[key] == value)
return query
params = {
'size': 'large',
'color': 'blue',
}
query = build_query(pieces_table, params)
print conn.execute(query).fetchall()