INTRODUCTION TO
SQLALCHEMY ORM
Created by /Jason A Myers @jasonamyers
WARNING!
SQLALCHEMY
Core - Schema centric
ORM - User Model
INSTALLING
pip install sqlalchemy
CONNECTING AND ESTABLISHING A
SESSION
CONNECTING
from sqlalchemy import create_engine
engine = create_engine('sqlite:///:memory:')
ESTABLISHING A SESSION
from sqlalchemy.orm import sessionmaker
Session = sessionmaker(bind=engine)
session = Session()
DEFINING MODELS
MODEL BASE
Declarative Base
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
COOKIE MODEL
from sqlalchemy import Column, Integer, Numeric, String
class Cookie(Base):
__tablename__ = 'cookies'
cookie_id = Column(Integer, primary_key=True)
cookie_name = Column(String(50), index=True)
cookie_recipe_url = Column(String(255))
cookie_sku = Column(String(55))
quantity = Column(Integer())
unit_cost = Column(Numeric(12, 2))
PERSISTING OUR TABLE
Base.metadata.create_all(engine)
INSERTING DATA
ADDING A COOKIE
cc_cookie = Cookie(cookie_name='chocolate chip',
cookie_recipe_url='http://some.aweso.me/cookie/recipe.html
cookie_sku='CC01',
quantity=12,
unit_cost=0.50)
ADDING TO SESSION
session.add(cc_cookie)
session.commit()
ACCESSING ATTRIBUTES
print(cc_cookie.cookie_id)
1
BULK INSERTS
c1 = Cookie(cookie_name='peanut butter',
cookie_recipe_url='http://some.aweso.me/cookie/peanut.html',
cookie_sku='PB01',
quantity=24,
unit_cost=0.25)
c2 = Cookie(cookie_name='oatmeal raisin',
cookie_recipe_url='http://some.okay.me/cookie/raisin.html',
cookie_sku='EWW01',
quantity=100,
unit_cost=1.00)
session.bulk_save_objects([c1,c2])
session.commit()
BULK INSERT DIFFERENCES
c1.cookie_id
QUERIES
ALL THE COOKIES!
cookies = session.query(Cookie).all()
print(cookies)
[Cookie(cookie_name='chocolate chip',
cookie_recipe_url='http://some.aweso.me/cookie/recipe.html',
cookie_sku='CC01', quantity=12, unit_cost=0.50),
Cookie(cookie_name='peanut butter',
cookie_recipe_url='http://some.aweso.me/cookie/peanut.html',
cookie_sku='PB01', quantity=24, unit_cost=0.25),
Cookie(cookie_name='oatmeal raisin',
cookie_recipe_url='http://some.okay.me/cookie/raisin.html',
cookie_sku='EWW01', quantity=100, unit_cost=1.00)]
ALL THE COOKIES! - ITERATOR
for cookie in session.query(Cookie):
print(cookie)
Cookie(cookie_name='chocolate chip',
cookie_recipe_url='http://some.aweso.me/cookie/recipe.html',
cookie_sku='CC01', quantity=12, unit_cost=0.50)
Cookie(cookie_name='peanut butter',
cookie_recipe_url='http://some.aweso.me/cookie/peanut.html',
cookie_sku='PB01', quantity=24, unit_cost=0.25)
Cookie(cookie_name='oatmeal raisin',
cookie_recipe_url='http://some.okay.me/cookie/raisin.html',
cookie_sku='EWW01', quantity=100, unit_cost=1.00)
PARTICULAR ATTRIBUTES
print(session.query(Cookie.cookie_name, Cookie.quantity).first())
('chocolate chip', 12)
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
DECENDING
from sqlalchemy import desc
for cookie in session.query(Cookie).order_by(desc(Cookie.quantity)):
print('{:3} - {}'.format(cookie.quantity, cookie.cookie_name))
LIMITING
query = session.query(Cookie).order_by(Cookie.quantity).limit(2)
print([result.cookie_name for result in query])
['chocolate chip', 'peanut butter']
DATABASE FUNCTIONS
from sqlalchemy import func
inv_count = session.query(func.sum(Cookie.quantity)).scalar()
print(inv_count)
136
DATABASE FUNCTIONS COUNT
rec_count = session.query(func.count(Cookie.cookie_name)).first()
print(rec_count)
(3, 0)
LABELING
rec_count = session.query(func.count(Cookie.cookie_name) 
.label('inventory_count')).first()
print(rec_count.keys())
print(rec_count.inventory_count)
['inventory_count']
5
FILTER_BY
record = session.query(Cookie). 
filter_by(cookie_name='chocolate chip').first()
print(record)
Cookie(cookie_name='chocolate chip',
cookie_recipe_url='http://some.aweso.me/cookie/recipe.html',
cookie_sku='CC01', quantity=12, unit_cost=0.50)
FILTER
record = session.query(Cookie). 
filter(Cookie.cookie_name == 'chocolate chip').first()
print(record)
CLAUSEELEMENTS
query = session.query(Cookie).filter(
Cookie.cookie_name.like('%chocolate%'))
for record in query:
print(record.cookie_name)
chocolate chip
CLAUSEELEMENT METHODS
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)
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
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
UPDATING COOKIES
UPDATING COOKIES
query = session.query(Cookie)
cc_cookie = query.filter(Cookie.cookie_name == "chocolate chip").first()
cc_cookie.quantity = cc_cookie.quantity + 120
session.commit()
print(cc_cookie.quantity)
132
DELETING COOKIES
DELETING COOKIES
query = session.query(Cookie)
query = query.filter(Cookie.cookie_name == "peanut butter")
dcc_cookie = query.one()
session.delete(dcc_cookie)
session.commit()
dcc_cookie = query.first()
print(dcc_cookie)
None
OKAY TIME FOR A BREATHER
RELATIONSHIPS
IMPORTS
from datetime import datetime
from sqlalchemy import DateTime, ForeignKey, Boolean
from sqlalchemy.orm import relationship, backref
USER MODEL
class User(Base):
__tablename__ = 'users'
user_id = Column(Integer(), primary_key=True)
username = Column(String(15), nullable=False, unique=True)
email_address = Column(String(255), nullable=False)
phone = Column(String(20), nullable=False)
password = Column(String(25), nullable=False)
created_on = Column(DateTime(), default=datetime.now)
updated_on = Column(DateTime(), default=datetime.now, onupdate=datetime.n
ORDER MODEL
class Order(Base):
__tablename__ = 'orders'
order_id = Column(Integer(), primary_key=True)
user_id = Column(Integer(), ForeignKey('users.user_id'))
shipped = Column(Boolean(), default=False)
user = relationship("User", backref=backref('orders', order_by=order_id)
LINEITEM MODEL
class LineItem(Base):
__tablename__ = 'line_items'
line_item_id = Column(Integer(), primary_key=True)
order_id = Column(Integer(), ForeignKey('orders.order_id'))
cookie_id = Column(Integer(), ForeignKey('cookies.cookie_id'))
quantity = Column(Integer())
extended_cost = Column(Numeric(12, 2))
order = relationship("Order", backref=backref('line_items', order_by=line
cookie = relationship("Cookie", uselist=False)
PERSIST THEM
Base.metadata.create_all(engine)
DEFINING A USER
cookiemon = User(username='cookiemon',
email_address='mon@cookie.com',
phone='111-111-1111',
password='password')
session.add(cookiemon)
session.commit()
SETTING UP AN ORDER
o1 = Order()
o1.user = cookiemon
session.add(o1)
PREPARING LINE ITEMS
cc = session.query(Cookie).filter(Cookie.cookie_name ==
"chocolate chip").one()
line1 = LineItem(cookie=cc, quantity=2, extended_cost=1.00)
pb = session.query(Cookie).filter(Cookie.cookie_name ==
"oatmeal raisin").one()
line2 = LineItem(quantity=12, extended_cost=3.00)
line2.cookie = pb
ASSOCIATE ORDER AND LINE ITEMS
o1.line_items.append(line1)
o1.line_items.append(line2)
session.commit()
USING RELATIONSHIPS IN QUERIES
query = session.query(Order.order_id, User.username, User.phone,
Cookie.cookie_name, LineItem.quantity,
LineItem.extended_cost)
query = query.join(User).join(LineItem).join(Cookie)
results = query.filter(User.username == 'cookiemon').all()
print(results)
[(1, 'cookiemon', '111-111-1111', 'chocolate chip', 2, Decimal('1.00')),
(1, 'cookiemon', '111-111-1111', 'oatmeal raisin', 12, Decimal('3.00'
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)
WHAT OTHER THINGS ARE OUT
THERE?
Automap
Geospatial Queries
QUESTIONS
Jason Myers / @jasonamyers / Essential SQLAlchemy

Introduction to SQLAlchemy ORM

  • 1.
    INTRODUCTION TO SQLALCHEMY ORM Createdby /Jason A Myers @jasonamyers
  • 2.
  • 3.
    SQLALCHEMY Core - Schemacentric ORM - User Model
  • 4.
  • 5.
  • 6.
    CONNECTING from sqlalchemy importcreate_engine engine = create_engine('sqlite:///:memory:')
  • 7.
    ESTABLISHING A SESSION fromsqlalchemy.orm import sessionmaker Session = sessionmaker(bind=engine) session = Session()
  • 8.
  • 9.
    MODEL BASE Declarative Base fromsqlalchemy.ext.declarative import declarative_base Base = declarative_base()
  • 10.
    COOKIE MODEL from sqlalchemyimport Column, Integer, Numeric, String class Cookie(Base): __tablename__ = 'cookies' cookie_id = Column(Integer, primary_key=True) cookie_name = Column(String(50), index=True) cookie_recipe_url = Column(String(255)) cookie_sku = Column(String(55)) quantity = Column(Integer()) unit_cost = Column(Numeric(12, 2))
  • 11.
  • 12.
  • 13.
    ADDING A COOKIE cc_cookie= Cookie(cookie_name='chocolate chip', cookie_recipe_url='http://some.aweso.me/cookie/recipe.html cookie_sku='CC01', quantity=12, unit_cost=0.50)
  • 14.
  • 15.
  • 16.
    BULK INSERTS c1 =Cookie(cookie_name='peanut butter', cookie_recipe_url='http://some.aweso.me/cookie/peanut.html', cookie_sku='PB01', quantity=24, unit_cost=0.25) c2 = Cookie(cookie_name='oatmeal raisin', cookie_recipe_url='http://some.okay.me/cookie/raisin.html', cookie_sku='EWW01', quantity=100, unit_cost=1.00) session.bulk_save_objects([c1,c2]) session.commit()
  • 17.
  • 18.
  • 19.
    ALL THE COOKIES! cookies= session.query(Cookie).all() print(cookies) [Cookie(cookie_name='chocolate chip', cookie_recipe_url='http://some.aweso.me/cookie/recipe.html', cookie_sku='CC01', quantity=12, unit_cost=0.50), Cookie(cookie_name='peanut butter', cookie_recipe_url='http://some.aweso.me/cookie/peanut.html', cookie_sku='PB01', quantity=24, unit_cost=0.25), Cookie(cookie_name='oatmeal raisin', cookie_recipe_url='http://some.okay.me/cookie/raisin.html', cookie_sku='EWW01', quantity=100, unit_cost=1.00)]
  • 20.
    ALL THE COOKIES!- ITERATOR for cookie in session.query(Cookie): print(cookie) Cookie(cookie_name='chocolate chip', cookie_recipe_url='http://some.aweso.me/cookie/recipe.html', cookie_sku='CC01', quantity=12, unit_cost=0.50) Cookie(cookie_name='peanut butter', cookie_recipe_url='http://some.aweso.me/cookie/peanut.html', cookie_sku='PB01', quantity=24, unit_cost=0.25) Cookie(cookie_name='oatmeal raisin', cookie_recipe_url='http://some.okay.me/cookie/raisin.html', cookie_sku='EWW01', quantity=100, unit_cost=1.00)
  • 21.
  • 22.
    ORDER BY for cookiein 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 importdesc for cookie in session.query(Cookie).order_by(desc(Cookie.quantity)): print('{:3} - {}'.format(cookie.quantity, cookie.cookie_name))
  • 24.
  • 25.
    DATABASE FUNCTIONS from sqlalchemyimport func inv_count = session.query(func.sum(Cookie.quantity)).scalar() print(inv_count) 136
  • 26.
    DATABASE FUNCTIONS COUNT rec_count= session.query(func.count(Cookie.cookie_name)).first() print(rec_count) (3, 0)
  • 27.
    LABELING rec_count = session.query(func.count(Cookie.cookie_name) .label('inventory_count')).first() print(rec_count.keys()) print(rec_count.inventory_count) ['inventory_count'] 5
  • 28.
    FILTER_BY record = session.query(Cookie). filter_by(cookie_name='chocolate chip').first() print(record) Cookie(cookie_name='chocolate chip', cookie_recipe_url='http://some.aweso.me/cookie/recipe.html', cookie_sku='CC01', quantity=12, unit_cost=0.50)
  • 29.
    FILTER record = session.query(Cookie). filter(Cookie.cookie_name == 'chocolate chip').first() print(record)
  • 30.
  • 31.
  • 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 importcast 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 importand_, 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
  • 35.
  • 36.
    UPDATING COOKIES query =session.query(Cookie) cc_cookie = query.filter(Cookie.cookie_name == "chocolate chip").first() cc_cookie.quantity = cc_cookie.quantity + 120 session.commit() print(cc_cookie.quantity) 132
  • 37.
  • 38.
    DELETING COOKIES query =session.query(Cookie) query = query.filter(Cookie.cookie_name == "peanut butter") dcc_cookie = query.one() session.delete(dcc_cookie) session.commit() dcc_cookie = query.first() print(dcc_cookie) None
  • 39.
    OKAY TIME FORA BREATHER
  • 40.
  • 41.
    IMPORTS from datetime importdatetime from sqlalchemy import DateTime, ForeignKey, Boolean from sqlalchemy.orm import relationship, backref
  • 42.
    USER MODEL class User(Base): __tablename__= 'users' user_id = Column(Integer(), primary_key=True) username = Column(String(15), nullable=False, unique=True) email_address = Column(String(255), nullable=False) phone = Column(String(20), nullable=False) password = Column(String(25), nullable=False) created_on = Column(DateTime(), default=datetime.now) updated_on = Column(DateTime(), default=datetime.now, onupdate=datetime.n
  • 43.
    ORDER MODEL class Order(Base): __tablename__= 'orders' order_id = Column(Integer(), primary_key=True) user_id = Column(Integer(), ForeignKey('users.user_id')) shipped = Column(Boolean(), default=False) user = relationship("User", backref=backref('orders', order_by=order_id)
  • 44.
    LINEITEM MODEL class LineItem(Base): __tablename__= 'line_items' line_item_id = Column(Integer(), primary_key=True) order_id = Column(Integer(), ForeignKey('orders.order_id')) cookie_id = Column(Integer(), ForeignKey('cookies.cookie_id')) quantity = Column(Integer()) extended_cost = Column(Numeric(12, 2)) order = relationship("Order", backref=backref('line_items', order_by=line cookie = relationship("Cookie", uselist=False)
  • 45.
  • 46.
    DEFINING A USER cookiemon= User(username='cookiemon', email_address='mon@cookie.com', phone='111-111-1111', password='password') session.add(cookiemon) session.commit()
  • 47.
    SETTING UP ANORDER o1 = Order() o1.user = cookiemon session.add(o1)
  • 48.
    PREPARING LINE ITEMS cc= session.query(Cookie).filter(Cookie.cookie_name == "chocolate chip").one() line1 = LineItem(cookie=cc, quantity=2, extended_cost=1.00) pb = session.query(Cookie).filter(Cookie.cookie_name == "oatmeal raisin").one() line2 = LineItem(quantity=12, extended_cost=3.00) line2.cookie = pb
  • 49.
    ASSOCIATE ORDER ANDLINE ITEMS o1.line_items.append(line1) o1.line_items.append(line2) session.commit()
  • 50.
    USING RELATIONSHIPS INQUERIES query = session.query(Order.order_id, User.username, User.phone, Cookie.cookie_name, LineItem.quantity, LineItem.extended_cost) query = query.join(User).join(LineItem).join(Cookie) results = query.filter(User.username == 'cookiemon').all() print(results) [(1, 'cookiemon', '111-111-1111', 'chocolate chip', 2, Decimal('1.00')), (1, 'cookiemon', '111-111-1111', 'oatmeal raisin', 12, Decimal('3.00'
  • 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)
  • 52.
    WHAT OTHER THINGSARE OUT THERE? Automap Geospatial Queries
  • 53.
    QUESTIONS Jason Myers /@jasonamyers / Essential SQLAlchemy