Keep data between requests in relational tables and ask for it with SQL.
Lectures this week
- Persistent Storage
- Mechanisms for Persistent Storage
- Relational Databases
- Relations
- ER Diagram
- SQL
Key points, notes and past questions
Databases, SQL & Flask-SQLAlchemy
Storing data and querying it from Flask.
- Start here: tables, rows and keys from zero
- Table = grid; row = one thing; column = one fact.
- Primary key: unique in every row.
- Foreign key: another table's primary key, a link.
- NULL means no value, not 0.
- Database families, graphs and indexes
- RDBMS: tables, keys, constraints, transactions.
- Key-value: one key → one value, fastest lookups.
- Graph: nodes + edges with properties; paths matter.
- Index: faster reads, slightly slower writes.
- SQL: WHERE, GROUP BY, HAVING, ORDER BY
- WHERE → GROUP BY → HAVING → SELECT → ORDER BY.
- Aggregates per group; HAVING filters groups.
- ASC = smallest first (the default).
- No aggregates in WHERE.
- SQLite's own behaviour
- Bare columns are allowed in SQLite.
- One-row group → exact value.
- Stored text keeps its case.
- LIKE ignores ASCII case; dates are text.
- Models and column options
- Every model needs a primary key.
- nullable defaults to True; mandatory = nullable=False.
- unique ≠ NOT NULL.
- Constructor: keyword arguments only.
- Default table name: snake_case of the class.
- Foreign keys and cardinality
- Key on the many side.
- Plain key → one-to-many; unique key → one-to-one.
- Association table → many-to-many.
- Key = db.Column(type, db.ForeignKey('lowercase_table.col')).
- The session: add, commit, update
- Model(k=v) → add → commit.
- first() = one object or None; all() = list.
- Change attributes, then commit, to update.
- rollback drops uncommitted changes.
- relationship(), backref, objects and ids
- Column ← id; relationship ← object.
- backref creates the other attribute; back_populates needs both sides.
- New objects have id None until written.
- uselist=False → one object, not a list.
- Queries: filter, filter_by, aggregates and dates
- filter_by: keywords, equality, AND.
- filter: expressions with &, and_(), |, or chained.
- Never Python
and/oron conditions. - Aggregates: query(func.max(col)).scalar().
- Dates: subtract in Python, not in SQLite SQL.
Notes32 past questions in this topic
Week 3: MVC & UI DesignWeek 5: Controllers & CRUDAll MAD 1 topics and weeks