Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.

Introduction to SQLAlchemy ORM

1,869 views

Published on

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.

Published in: Technology

Introduction to SQLAlchemy ORM

  1. 1. INTRODUCTION TO SQLALCHEMY ORM Created by /Jason A Myers @jasonamyers
  2. 2. WARNING!
  3. 3. SQLALCHEMY Core - Schema centric ORM - User Model
  4. 4. INSTALLING pip install sqlalchemy
  5. 5. CONNECTING AND ESTABLISHING A SESSION
  6. 6. CONNECTING from sqlalchemy import create_engine engine = create_engine('sqlite:///:memory:')
  7. 7. ESTABLISHING A SESSION from sqlalchemy.orm import sessionmaker Session = sessionmaker(bind=engine) session = Session()
  8. 8. DEFINING MODELS
  9. 9. MODEL BASE Declarative Base from sqlalchemy.ext.declarative import declarative_base Base = declarative_base()
  10. 10. 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))
  11. 11. PERSISTING OUR TABLE Base.metadata.create_all(engine)
  12. 12. INSERTING DATA
  13. 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. 14. ADDING TO SESSION session.add(cc_cookie) session.commit()
  15. 15. ACCESSING ATTRIBUTES print(cc_cookie.cookie_id) 1
  16. 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. 17. BULK INSERT DIFFERENCES c1.cookie_id
  18. 18. QUERIES
  19. 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. 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. 21. PARTICULAR ATTRIBUTES print(session.query(Cookie.cookie_name, Cookie.quantity).first()) ('chocolate chip', 12)
  22. 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. 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))
  24. 24. LIMITING query = session.query(Cookie).order_by(Cookie.quantity).limit(2) print([result.cookie_name for result in query]) ['chocolate chip', 'peanut butter']
  25. 25. DATABASE FUNCTIONS from sqlalchemy import func inv_count = session.query(func.sum(Cookie.quantity)).scalar() print(inv_count) 136
  26. 26. DATABASE FUNCTIONS COUNT rec_count = session.query(func.count(Cookie.cookie_name)).first() print(rec_count) (3, 0)
  27. 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. 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. 29. FILTER record = session.query(Cookie). filter(Cookie.cookie_name == 'chocolate chip').first() print(record)
  30. 30. CLAUSEELEMENTS query = session.query(Cookie).filter( Cookie.cookie_name.like('%chocolate%')) for record in query: print(record.cookie_name) chocolate chip
  31. 31. CLAUSEELEMENT METHODS
  32. 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. 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. 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
  35. 35. UPDATING COOKIES
  36. 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. 37. DELETING COOKIES
  38. 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. 39. OKAY TIME FOR A BREATHER
  40. 40. RELATIONSHIPS
  41. 41. IMPORTS from datetime import datetime from sqlalchemy import DateTime, ForeignKey, Boolean from sqlalchemy.orm import relationship, backref
  42. 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. 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. 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. 45. PERSIST THEM Base.metadata.create_all(engine)
  46. 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. 47. SETTING UP AN ORDER o1 = Order() o1.user = cookiemon session.add(o1)
  48. 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. 49. ASSOCIATE ORDER AND LINE ITEMS o1.line_items.append(line1) o1.line_items.append(line2) session.commit()
  50. 50. 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'
  51. 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. 52. WHAT OTHER THINGS ARE OUT THERE? Automap Geospatial Queries
  53. 53. QUESTIONS Jason Myers / @jasonamyers / Essential SQLAlchemy

×