I'm trying to generate a certain SQL statement with SQLAlchemy where there is an existing schema and data inside the database. I approach it like this:
from sqlalchemy.orm import sessionmaker
from sqlalchemy import create_engine, Table
from sqlalchemy.ext.declarative import declarative_base
Session = sessionmaker()
engine = create_engine('sqlite:///example.db')
Session.configure(bind=engine)
session = Session()
base = declarative_base()
base.metadata.reflect(engine)
table = Table('dane', base.metadata, autoload=True)
q = session.query(table).filter(table.c.title == 'A')
print(q)
When I examine the rendered (generated) query from the above code it generates this:
SELECT dane.title AS dane_title, dane.body AS dane_body
FROM dane
WHERE dane.title = ?
I do not need, however, a dynamic statement, I need the ?
in the query to be exactly A
as would the .filter
call suggest. How can I achieve a constant WHERE
expression with SQLAlchemy?
UPDATE
SA actually does generate constant WHERE conditions. To see them you need to pass special kwargs to compile():
.compile(compile_kwargs={"literal_binds": True})
as in @metatoaster's answer below.