Execute Raw SQL In Flask SQLAlchemy

Feb 13, 2018

If you want to return the result as Models.

from sqlalchemy.sql import textfrom app.models import Notificationsql = """SELECT *FROM notificationWHERE id > :id"""notifications = session.query(Notification).from_statement(text(sql)).params(id=5).all()

NOTE: dict {"id":5} or named parameters id=5 works.

If you want to return the result as tuple/dict.

sql = """SELECT *FROM notificationWHERE id > :id"""# db is SQLAlchemy objectresults = db.engine.execute(text(sql), {"id":5})for _result in results:    print(_result['id'])    print(_result[0])    print(_result)

You can use session as well.

results = session.execute(text(sql), id=5)for _result in results:    print(_result['id'])

❤️ Is this article helpful?

Buy me a coffee ☕ or support my work via PayPal to keep this space 🖖 and ad-free.

Do send some 💖 to @d_luaz or share this article.

✨ By Desmond Lua

A dream boy who enjoys making apps, travelling and making youtube videos. Follow me on @d_luaz

👶 Apps I built

Travelopy - discover travel places in Malaysia, Singapore, Taiwan, Japan.