SQL Alchemy

  • ORM for SQL python

  • 2.0 released 1/26/23 which recommends usage of select instead of query, so most guides are out of date

See flask/sqlalchemy for more

pip install sqlalchemy
# For PostgreSQL
pip install psycopg2
# For MySQL
pip install pymysql

Usage

Querying

from sqlalchemy import select

user = db.session.scalars(select(User).where(User.email == email)).first()


# query with multiple classes, returns list of tuples
result = session.execute(select(User, Address).join("addresses").filter_by(name="ed")).all()

# query with ORM columns, returns list of tuples
result = session.execute(select(User.name, User.fullname)).all()

# Joins, infers the on statement
users = db.session.scalars(select(User).join(Cohort).join(School).where(School.id == school_id)).all()

Insert

Insert parent and children

Models

Relationships

One to many

  • "Child" and "Parent" are the names of the table not type of relation

  • back_populates uses the variable inside the class as the thing in strings

Migrating/Creating Tables

Very Rough Code that creates table

Recommended to use flask-migrate or

Outside of Flask

Session

Must use session for all transactions and session.commit if you write data

Last updated