SQLAlchemy Query Cheatsheet

back
The common SQLAlchemy queries.
Chen, 2020-11-07

EQUAL:

query.filter(Matrix.location == 'zurich')

NOT EQUAL:

query.filter(Matrix.location != 'zurich')

LIKE:

query.filter(Matrix.location.like('%zurich%'))

IN:

query.filter(Matrix.location.in_(['zurich', 'london', 'berlin']))

NOT IN:

query.filter(~Matrix.location.in_(['zurich', 'london', 'berlin']))

IS NULL:

filter(Matrix.location == None)

IS NOT NULL:

filter(Matrix.location != None)

AND:

# use and_
from sqlalchemy import and_
filter(and_(Matrix.location == 'zurich', Matrix.name == 'firebase'))

# use ,
filter(Matrix.location == 'zurich', Matrix.name == 'firebase')

# chain filters
filter(Matrix.location == 'zurich').filter(Matrix.name == 'firebase')

OR:

from sqlalchemy import or_
filter(or_(Matrix.location == 'zurich', Matrix.location == 'akshay'))

MATCH:

query.filter(Matrix.location.match('zurich'))