SQLAlchemy is a popular database framework that provides an ORM and a schema centric query language, and in this talk we will take a look how to get started with the ORM. We'll learn how to establish connections to popular databases such as PostgreSQL and MySQL. Then we will look at how to define our models as user classes including relationships and persist them to the database. Next, we'll cover the how the SQLAlchemy session works with typical create, update, read, and delete operations. We'll wrap up with pointers of where to go next to learn more.
22. ORDER BY
for cookie in session.query(Cookie).order_by(Cookie.quantity):
print('{:3} - {}'.format(cookie.quantity, cookie.cookie_name))
12 - chocolate chip
24 - peanut butter
100 - oatmeal raisin
23. DECENDING
from sqlalchemy import desc
for cookie in session.query(Cookie).order_by(desc(Cookie.quantity)):
print('{:3} - {}'.format(cookie.quantity, cookie.cookie_name))
32. between(cleft, cright) - Find where the column is between
cleft and cright
distinct() - Find only unique values for column
in_([list]) - Find where the column is in the list
is_(None) - Find where the column is None (commonly
used for Null checks with None)
contains('string') - Find where the column has 'string' in it
(Case-sensitive)
endswith('string') - Find where the column ends with
'string' (Case-sensitive)
startswith('string') - Find where the column begins with
'string' (Case-sensitive)
ilike('string') - Find where the column is like 'string' (NOT
Case-sensitive)
33. OPERATORS
from sqlalchemy import cast
query = session.query(Cookie.cookie_name,
cast((Cookie.quantity * Cookie.unit_cost),
Numeric(12,2)).label('inv_cost'))
for result in query:
print('{} - {}'.format(result.cookie_name, result.inv_cost))
chocolate chip - 6.00
peanut butter - 6.00
oatmeal raisin - 100.00
34. CONJUNCTIONS
from sqlalchemy import and_, or_, not_
query = session.query(Cookie).filter(
or_(
Cookie.quantity.between(10, 50),
Cookie.cookie_name.contains('chip')
)
)
for result in query:
print(result.cookie_name)
chocolate chip
peanut butter
51. ANOTHER EXAMPLE
query = session.query(User.username, func.count(Order.order_id))
query = query.outerjoin(Order).group_by(User.username)
for row in query:
print(row)
('cookiemon', 1)