Slides: https://docs.google.com/presentation/d/1SMtBILSrqt9SWK5BnEKe4ivGTHItrVjgCEB0AUhGeyM
$ python -m venv venv
$ venv/bin/pip install sqlalchemy colorama
# Install ipython
$ venv/bin/pip install ipython
# Start a terminal
$ venv/bin/ipython
from app import db
from models import Author, Book, Series
tolkien = Author(name='J R R Tolkien')
lotr = Series(name='Lord of the Rings', books=[
Book(name='Fellowship of the Ring', authors=[tolkien]),
Book(name='Two Towers', authors=[tolkien]),
Book(name='Return of the King', authors=[tolkien]),
])
db.add(lotr)
adams = Author(name='Douglas Adams')
h2g2 = Series(name='Hitchhiker\'s Guide to the Galaxy', books=[
Book(name='Hitchhiker\'s Guide to the Galaxy', authors=[adams]),
Book(name='Restaurant at the End of the Universe', authors=[adams]),
Book(name='Life, Universe and Everything', authors=[adams]),
Book(name='So Long, and Thanks for All the Fish', authors=[adams]),
Book(name='Mostly Harmless', authors=[adams]),
Book(name='And Another Thing...', authors=[adams]),
])
db.add(h2g2)
wells = Author(name='HG Wells')
time_machine = Book(name='Time Machine', authors=[wells])
db.add(time_machine)
ditko = Author(name='Steve Ditko')
stanlee = Author(name='Stan Lee')
spider_man = Book(name='Spider Man', authors=[ditko, stanlee])
db.add(spider_man)
Import the Models:
from app import db
from models import Author, Book, Series
Querying with sqlalchemy:
Author.query.all()
# WHERE conditions
Author.query.filter_by(name='a').all()
# Access relationships
author = Author.query.first()
author.books
# Count number of books
{a: len(a.books) for a in Author.query.all()}
# Change the loading strategy
from sqlalchemy.orm import joinedload
{a: len(a.books) for a in Author.query.options(joinedload(Author.books)).all()}