Storing data and querying it from Flask.
Open the interactive lessons →Databases, SQL & Flask-SQLAlchemy past questions
Contents
- Start here: tables, rows and keys from zero
- Database families, graphs and indexes
- SQL: WHERE, GROUP BY, HAVING, ORDER BY
- SQLite's own behaviour
- Models and column options
- Foreign keys and cardinality
- The session: add, commit, update
- relationship(), backref, objects and ids
- Queries: filter, filter_by, aggregates and dates
1. Start here: tables, rows and keys from zero
A table is a grid; a key finds one row; a foreign key points at a row in another table.
how a relational database lays out data
The question this lesson answers. Why store a number such as 10 in a student's row instead of the course's name, and how do you get the name back?
A relational database keeps data in tables. Each table is about one kind of thing. Each row is one of those things and each column is one fact about it. A web app reads and writes these rows on every request; the database is what remembers between requests.
A table, read like a grid
| s_id (primary key) | name | course_id (foreign key) |
|---|---|---|
| 1 | Asha | 10 |
| 2 | Ravi | 10 |
| 3 | Meera | 20 |
The primary key (here s_id) is different in every row, so it finds exactly one row. A foreign key (here course_id) stores the primary key of a row in another table (course), which links each student to one course. Two students with course 10 means one course has many students.
A table is a class register. The roll number is the primary key: no two students share it. Writing a teacher's staff number next to each student is a foreign key: it points at a row in the staff register instead of copying the teacher's details. The analogy stops at order: a register has a fixed order, a table does not.
Follow a key from one table to the other. The course table holds (10, Web) and (20, DB). Zoya has no course yet.
Worked example: Find the keys
Problem.
Tables: course(id, title) and enrollment(id, student_name, course_id).
Idea.
Primary key = unique id of its own table; foreign key = another table's id.
- course.id is course's primary key.
- enrollment.id is enrollment's primary key.
- enrollment.course_id stores a course.id: it is a foreign key.
Answer.
course.id and enrollment.id are primary keys; enrollment.course_id is a foreign key
Common mistake.
Calling course_id a primary key because it ends in id.
Worked example: Read the link
Problem.
course rows: (10, Web), (20, DB). enrollment rows: (1, Asha, 10), (2, Ravi, 10), (3, Meera, 20).
Idea.
Count rows whose foreign key equals the course's id.
- Web has id 10.
- Rows with course_id 10: Asha and Ravi, so 2.
- Each enrollment has one course, a course has many enrollments: one-to-many.
Answer.
2 enrollments; one-to-many
Common mistake.
Counting rows by course title, which enrollment does not store.
Worked example: A name stored twice
Problem.
A table stores the course title in every enrolment row. The title of one course changes. What can go wrong?
Idea.
One fact should live in one place.
- Every matching row must be edited.
- If one row is missed, the same course now has two names.
- Storing the id means only the course row changes.
Answer.
The data can become inconsistent.
Common mistake.
Thinking a repeated title is harmless because it is easier to read.
- Read a question's tables by marking the primary key of each, then draw an arrow for every foreign key.
- A many-to-many link needs a third table that holds two foreign keys.
NULLis tested withIS NULL. The comparison= NULLmatches nothing.
Store the key once, follow it whenever you need the details.
Method for any exam question
| Step | Do this |
|---|---|
| 1 | Find the primary key of each table. |
| 2 | Find which column points to another table. |
| 3 | Match values to follow the link. |
| 4 | Treat NULL as no link. |
2. Database families, graphs and indexes
Pick the database by the shape of the question you will ask it.
which kind of database fits which job
The question this lesson answers. Which kind of database fits a job, and why does an index make a search fast without changing the answer?
Four families
| Family | Stores | Best for | Example |
|---|---|---|---|
| Relational (RDBMS) | tables, rows, foreign keys | structured data, many links, constraints, transactions | SQLite, MySQL, PostgreSQL |
| Key-value | key → value | one quick lookup by key, caches, sessions | Redis, DynamoDB |
| Document | JSON-like documents | flexible, nested records | MongoDB |
| Graph | nodes and edges with properties | paths: friends of friends, routes | Neo4j |
An index is a sorted (or hashed) copy of one or more columns that points back to the rows, so a lookup jumps to the right rows instead of reading the whole table. Reads get faster; every insert or update also updates the index.
A key-value store is a coat-check counter: hand over the ticket number, get the coat. A relational database is the college office's filing system, with forms that refer to each other. A graph is the map of who knows whom. The analogy stops at speed: a real RDBMS with an index is also fast for single lookups.
Worked example: Coupon check
Problem.
At checkout a shop must answer very fast: "has this coupon code already been used?"
Idea.
The question is one key in, one value out.
- Key: the coupon code.
- Value: used or not.
- No joins or ranges are needed.
Answer.
Key-value store
Common mistake.
Picking an RDBMS because the rest of the shop uses one.
Worked example: Which statements fit a graph?
Problem.
(A) A metro map can be stored as a graph. (B) An edge can carry a distance. (C) Finding a shortest route between stations suits a graph database. (D) A graph database stores everything as fixed rows and columns.
Idea.
A graph is nodes and edges with properties, used for following paths.
- A true: stations are nodes, tracks are edges.
- B true: edges hold properties.
- C true: this is a path query.
- D describes a relational table.
Answer.
A, B, C
Common mistake.
Rejecting B because only nodes "hold data".
Seeing an index work. SQLite can tell you how it plans to answer a query: put EXPLAIN QUERY PLAN in front of it. Without an index on the column you search, the plan says SCAN: read every row. After CREATE INDEX ix ON u(email) the same query says SEARCH ... USING INDEX: jump straight to the matching rows. (SQLite writes COVERING INDEX when the index alone holds every column the query needs.)
EXPLAIN QUERY PLAN SELECT * FROM u WHERE email = 'u5@x';
-- SCAN u
CREATE INDEX ix ON u(email);
EXPLAIN QUERY PLAN SELECT * FROM u WHERE email = 'u5@x';
-- SEARCH u USING COVERING INDEX ix (email=?)
Family by the question you ask
| Question your app asks most | Best family | Why |
|---|---|---|
| "Give me user 42's cart" | key-value | one key, one value, very fast |
| "Orders with their customer and items, all or nothing" | relational | joins and transactions |
| "Products whose fields differ a lot" | document | no fixed columns |
| "Friends of friends within 3 steps" | graph | paths are first-class |
Worked example: An index on the wrong column
Problem.
An index exists on email. The query filters on name. Does the index help?
Idea.
An index is sorted by its own columns.
- The search condition uses
name. - The index is ordered by
email. - It cannot be used to find a name, so the table is scanned.
Answer.
No.
Common mistake.
Assuming any index speeds up every query on that table.
- Match the clue: transactions or joins point to RDBMS, one key to one value points to key-value, paths between things point to graph.
- An index makes reads faster but costs extra space and slower writes.
- Reject options that say one database family is always best.
Choose the family by the question; index the column you search by.
Method for any exam question
| Step | Do this |
|---|---|
| 1 | Name the question the application asks most. |
| 2 | One key to one value suggests key-value. |
| 3 | Links and constraints suggest relational. |
| 4 | Relationships of relationships suggest a graph. |
3. SQL: WHERE, GROUP BY, HAVING, ORDER BY
Filter rows, make groups, filter groups, sort.
the order in which a SELECT runs
The question this lesson answers. A query is written in one order but carried out in another. Which rows are still there at each stage?
Sorting receipts: first throw away the ones you do not need, then make a pile per shop, then drop piles that are too small, then read them in order.
The sales table
| shop | item | qty | price |
|---|---|---|---|
| North | Pen | 4 | 10 |
| South | Bag | 2 | 300 |
| North | Ruler | 12 | 15 |
| East | Lamp | 25 | 220 |
| South | Cap | 6 | 120 |
| East | Fan | 40 | 900 |
| West | Mug | 30 | 80 |
SELECT Manufacturer, COUNT(*)
FROM production
WHERE Quantity > 10
GROUP BY Manufacturer
HAVING COUNT(*) = 2;
Worked example: Count per genre
Problem.
Table loans has genre Poetry on 5 rows, History on 3 and Maths on 2. SELECT genre, COUNT(id) AS n FROM loans GROUP BY genre ORDER BY n ASC;
Idea.
One row per group, sorted by the alias.
- Counts: Poetry 5, History 3, Maths 2.
- ASC puts the smallest first.
Answer.
Maths 2, History 3, Poetry 5
Common mistake.
Listing one row per loan, or sorting descending.
Worked example: HAVING after WHERE
Problem.
On sales: SELECT shop, COUNT(*) FROM sales WHERE qty > 10 GROUP BY shop HAVING COUNT(*) = 2;
Idea.
Counts are over the rows that passed WHERE.
- Rows with qty above 10: Ruler (North), Lamp (East), Fan (East), Mug (West).
- North 1, East 2, West 1.
- Only East has a count of 2.
Answer.
East | 2
Common mistake.
Counting all seven rows first, which would also keep North and South.
An aggregate cannot go in WHERE: WHERE COUNT(*) > 1 is an error ("misuse of aggregate"). Conditions on groups go in HAVING.
Three details that change answers. Several sort keys are applied left to right. COUNT(DISTINCT col) counts different values, not rows. And in WHERE, AND binds tighter than OR, exactly like × before + in arithmetic: brackets change the result.
On the sales table (4 shops; 7 rows)
| Query part | Result |
|---|---|
ORDER BY shop DESC, qty ASC | West first; inside East, Lamp (25) before Fan (40) |
SELECT COUNT(DISTINCT shop), COUNT(*) | 4, 7 |
WHERE shop='North' OR shop='South' AND qty>4 | Pen, Ruler, Cap (all of North, plus South with qty above 4) |
WHERE (shop='North' OR shop='South') AND qty>4 | Ruler, Cap |
ORDER BY price DESC LIMIT 2 | Fan, Bag |
Worked example: Where do the brackets go?
Problem.
You want North or South items with quantity above 4. Someone writes WHERE shop='North' OR shop='South' AND qty>4.
Idea.
AND is applied first: shop='North' OR (shop='South' AND qty>4).
- Pen (North, qty 4) passes through the left side although 4 is not above 4.
- Fix:
WHERE (shop='North' OR shop='South') AND qty>4. - Now only Ruler and Cap remain.
Answer.
Without brackets: Pen, Ruler, Cap; with brackets: Ruler, Cap
Common mistake.
Reading the condition left to right as if OR came first.
Joining two tables. Data about one thing is split across tables and linked by keys, so most real questions need a JOIN. JOIN ... ON e.course_id = c.id pairs each enrollment with its course. An inner join keeps only rows that have a partner; a LEFT join keeps every row of the left table, with NULL where there is no partner, which is how you count zeros.
SELECT e.name, c.title
FROM enrollment e JOIN course c ON e.course_id = c.id;
-- Asha Web, Ravi Web, Meera DB (Zoya has no course: left out)
SELECT c.title, COUNT(e.id)
FROM course c LEFT JOIN enrollment e ON e.course_id = c.id
GROUP BY c.id;
-- Web 2, DB 1, AI 0
Worked example: Courses with no students
Problem.
course: Web (10), DB (20), AI (30). enrollment course_ids: 10, 10, 20, NULL.
Idea.
Only a LEFT join keeps a course with no partner.
- Inner join drops AI (no enrollment points at 30).
- LEFT JOIN from course keeps AI with NULLs.
- COUNT(e.id) counts non-NULL ids: 0.
Answer.
LEFT JOIN; AI 0
Common mistake.
Using COUNT(*) with the left join: it counts the NULL row as 1.
Worked example: Two kinds of count
Problem.
In enrollment, one of the four rows has course_id NULL. What does SELECT COUNT(*), COUNT(course_id) FROM enrollment return?
Idea.
COUNT(column) skips NULL.
COUNT(*)counts rows: 4.COUNT(course_id)counts non-NULL values: 3.
Answer.
4 and 3.
Common mistake.
Answering 4 for both.
- Solve in running order: filter rows, group, filter groups, pick columns, sort.
COUNT(*)counts rows;COUNT(column)skips rows where that column isNULL.- Write the small intermediate table after
WHEREbefore you group. It prevents most counting slips.
FROM, WHERE, GROUP BY, HAVING, SELECT, ORDER BY.
Method for any exam question
| Step | Do this |
|---|---|
| 1 | Write the starting rows. |
| 2 | Cross out rows that fail WHERE. |
| 3 | Group what is left. |
| 4 | Cross out groups that fail HAVING. |
| 5 | Compute the columns, then sort. |
4. SQLite's own behaviour
SQLite is lenient: bare columns, case-insensitive LIKE, dates as text.
what SQLite does that stricter databases refuse
The question this lesson answers. Where does SQLite behave differently from what you expect? Predict each result before revealing it: 1 means true, 0 means false.
A relaxed shopkeeper: SQLite accepts requests that stricter databases refuse, so you must know what it hands back.
Select count(ID), Name, color from flowers
group by color HAVING count(color)<2;
Bare column in a GROUP BY
| SQLite | PostgreSQL / strict SQL | |
|---|---|---|
SELECT Name, color ... GROUP BY color | allowed | error: Name must be grouped or aggregated |
| one-row group | that row's Name | not run |
| bigger group | a Name from one of its rows | not run |
Worked example: Exact spelling
Problem.
The stored name is "Red rose". An option shows "red rose".
Idea.
SQL returns stored text unchanged.
- SELECT does not change case.
- "red rose" ≠ "Red rose".
Answer.
No
Common mistake.
Treating names as case-insensitive.
Worked example: One-row groups
Problem.
Table pets (name, kind): Bruno dog, Tommy dog, Big Ben fish, Simba dog, Milo cat. SELECT COUNT(*), name, kind FROM pets GROUP BY kind HAVING COUNT(kind) < 2;
Idea.
Keep one-row groups, then read their rows.
- Groups: cat 1, dog 3, fish 1.
- Keep cat and fish.
- SQLite gives the groups ordered by kind, with the stored spelling.
Answer.
1|Milo|cat, 1|Big Ben|fish
Common mistake.
Including dog, or writing big ben in lower case.
Two more SQLite habits that show up in ORM questions: LIKE 'p%' also matches 'P...' , and dates are stored as text, so fixed_at - broken_at in SQL subtracts the years only.
Types and NULL in SQLite. SQLite stores a value with its own type. A column declared INTEGER converts text that looks like a number ('5' becomes 5) and keeps other text as text. Text compares letter by letter, so '10' < '9'. And NULL is not equal to anything, not even NULL: x = NULL is never true; write x IS NULL.
Surprises, run on SQLite
| Expression | Result | Why |
|---|---|---|
'10' < '9' | true (1) | text compares '1' with '9' first |
10 < 9 | false (0) | numbers compare as numbers |
NULL = NULL | NULL (unknown) | nothing equals an unknown value |
WHERE x = NULL | no rows | use WHERE x IS NULL |
| insert '5' and 'abc' into an INTEGER column | 5 (integer), 'abc' (text) | type affinity |
Worked example: Count the missing values
Problem.
Table n has x values 1, NULL, 3.
Idea.
= NULL is never true; IS NULL tests for it.
- x = NULL is unknown for every row, so nothing is counted: 0.
- x IS NULL is true for one row: 1.
Answer.
0 and 1
Common mistake.
Writing = NULL and expecting it to find the empty value.
Worked example: A number column holding text
Problem.
A column is declared INTEGER. SQLite is given '12' and then 'abc'. What types are stored?
Idea.
SQLite converts text only when it looks like a number.
'12'is converted to an integer.'abc'cannot be converted and stays text.
Answer.
integer, then text.
Common mistake.
Expecting an error for the second insert.
- With a single
MINorMAX, SQLite takes a bare column from the row that holds that value. =is case-sensitive for text, whileLIKEignores the case of ASCII letters.- Dates stored as
YYYY-MM-DDtext compare correctly as text.
Check the type, the case and the NULL.
Method for any exam question
| Step | Do this |
|---|---|
| 1 | Decide whether each value is text or a number. |
| 2 | Note = against LIKE for capitals. |
| 3 | Replace any NULL comparison by IS NULL. |
| 4 | Then compute the result. |
5. Models and column options
Class = table, attribute = column, and one column is the primary key.
how a class describes a table
The question this lesson answers. You declare rules on a column. Which inserts does the database really refuse?
A model is a printed form: each column is a box, with rules such as "must be filled" or "no two alike".
class MaxScores(db.Model):
course_id = db.Column(db.String(10), primary_key=True)
high_score = db.Column(db.Integer)
MaxScores.__tablename__ # 'max_scores'
MaxScores(course_id='cs2002', high_score=86) # fine
MaxScores('cs2002', 86) # TypeError
Column options
| Option | Means | Default |
|---|---|---|
primary_key=True | identifies the row; NOT NULL | False (one column must be True) |
nullable=False | value required ("mandatory") | True for other columns |
unique=True | no two rows equal (NULL still allowed) | False |
db.ForeignKey('table.col') | value must match a row in another table | none |
autoincrement | integer key filled automatically | integer primary keys get one |
Worked example: Mandatory and optional
Problem.
A product needs: sku integer primary key; title mandatory text; discount optional number.
Idea.
Mandatory means nullable=False; a column is optional unless you say otherwise.
sku = db.Column(db.Integer, primary_key=True)title = db.Column(db.String, nullable=False)discount = db.Column(db.Float)(the same asnullable=True).
Answer.
Writing nullable=True on discount, or leaving it out, are both correct
Common mistake.
Using unique=True where primary_key=True is needed: a model with no primary key does not map.
Worked example: Match a CREATE TABLE
Problem.
CREATE TABLE "Books" ("book_id" INTEGER, "title" TEXT, "pages" INTEGER, PRIMARY KEY("book_id")). You are shown several declarative classes.
Idea.
Compare table name, column names, types and primary key, one at a time.
__tablename__must be"Books"; the Python class name may differ.- The attributes are
book_id,title,pages. primary_key=Truesits onbook_idonly.
Answer.
__tablename__ = "Books", book_id (Integer, primary key), title (String), pages (Integer)
Common mistake.
Judging by the class name instead of __tablename__.
What the database actually enforces. Column options are only as strong as the database behind them. SQLite enforces primary keys, NOT NULL and UNIQUE, but it does not enforce a string length: db.String(5) happily stores a much longer text. On PostgreSQL or MySQL the same model would reject it.
Declared versus enforced on SQLite
| Option | Enforced by SQLite? | What happens if broken |
|---|---|---|
primary_key=True | yes | IntegrityError on a duplicate |
nullable=False | yes | IntegrityError on NULL |
unique=True | yes | IntegrityError on a duplicate |
db.String(5) | no | the long text is stored as it is |
Worked example: A length that is not checked
Problem.
s = db.Column(db.String(5)). You add T(s="much longer than five") and commit on SQLite.
Idea.
SQLite ignores the declared length.
- The commit succeeds.
- Reading it back gives the full text.
Answer.
much longer than five
Common mistake.
Expecting truncation to 5 characters or an error: that happens on stricter databases, not SQLite.
Worked example: A default that is not there yet
Problem.
A column has default=5. What is the attribute on a new object before it is saved?
Idea.
The default is applied when the row is inserted.
- The object has only been created in Python.
- No insert has happened.
Answer.
None
Common mistake.
Expecting 5 immediately.
The setup that comes before any model. Past questions often begin with these lines and expect you to read them at a glance.
Connect Flask to a SQLite file
import os
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
app_dir = os.path.abspath(os.path.dirname(__file__))
db_file = os.path.join(app_dir, "school.sqlite3")
app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:///" + db_file
db = SQLAlchemy(app)
class Student(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(40))
with app.app_context():
db.create_all()
| Line | What it does |
|---|---|
from flask_sqlalchemy import SQLAlchemy | imports the extension; the package name uses an underscore |
os.path.dirname(__file__) | the folder that holds this Python file |
os.path.abspath(...) | turns it into a full path from the root of the disk |
os.path.join(app_dir, "school.sqlite3") | full path of the database file |
SQLALCHEMY_DATABASE_URI | tells the extension which database to open; sqlite:/// comes before the file path |
db = SQLAlchemy(app) | creates the object that gives you db.Model, db.Column and db.session |
with app.app_context(): | database work outside a request needs to know which app it belongs to |
db.create_all() | creates the tables that do not exist yet; it does not change a table that already exists |
Two other spellings mean the same thing. You may see db = SQLAlchemy() followed later by db.init_app(app), or app.app_context().push() in place of the with block. A short URI such as sqlite:///school.sqlite3 is a relative path; Flask-SQLAlchemy 3 places that file in the app's instance folder. You may also see SQLALCHEMY_TRACK_MODIFICATIONS = False, which only switches off change notifications and does not affect queries.
Worked example: Why does this script crash?
Problem.
A script sets the URI, creates db, defines Student and then calls db.create_all() directly at the top level, outside any route.
Idea.
Ask whether Flask knows which app is active at that line.
- No request is running, so no application context exists.
- Flask-SQLAlchemy raises a
RuntimeErrorsaying it is working outside of the application context. - Wrap the call in
with app.app_context():.
Answer.
RuntimeError; call create_all inside the app context.
Common mistake.
Blaming the model class. The model is fine; the context is missing.
- Scan every column for
nullable=Falseandunique=Truebefore judging whether an insert fails. - Without
__tablename__, turn the class name into lower snake case to find the table name. - Arguments to a model are given by name, such as
Student(name="A").
A declaration is a promise only if the database enforces it.
Method for any exam question
| Step | Do this |
|---|---|
| 1 | Find the primary key. |
| 2 | Mark columns that refuse NULL. |
| 3 | Check for unique columns. |
| 4 | Remember that SQLite ignores string length. |
6. Foreign keys and cardinality
Find the foreign key; its side and its uniqueness give the answer.
reading a relationship's type from the model code
The question this lesson answers. Looking only at the model code, how can you tell whether one row links to one, to many, or many to many? The foreign key tells you.
In a one-to-many link each child carries a card naming its one parent. In many-to-many neither side can carry all the cards, so a separate list records the pairs.
Read the key
| What you see | Relationship |
|---|---|
child.parent_id = Column(..., ForeignKey('parent.id')) | one parent → many children |
same, with unique=True (and uselist=False on the relationship) | one-to-one |
| third table with two foreign keys (product_id, supplier_id) | many-to-many |
| no foreign key between the tables | not related (a matching name is not enough) |
class Parent(Base):
__tablename__ = "parent_table"
id = Column(Integer, primary_key=True)
children = relationship("Child")
class Child(Base):
__tablename__ = "child_table"
id = Column(Integer, primary_key=True)
parent_id = Column(Integer, ForeignKey("parent_table.id"))
Worked example: Playlist and Song
Problem.
Song.playlist_id = db.Column(db.Integer, db.ForeignKey("playlist.id")), not unique.
Idea.
A plain foreign key sits on the many side.
- Song holds the key, so Song is the many side.
- Not unique, so many songs can store the same playlist id.
Answer.
One playlist to many songs
Common mistake.
Saying many-to-many from real-life playlists; this design has no association table.
Worked example: Citizen and Passport
Problem.
Passport.citizen_id = db.Column(db.Integer, db.ForeignKey("citizen.id"), unique=True).
Idea.
A unique foreign key.
- The key links the two tables.
unique=True: each citizen id can appear once inpassport.- So a citizen has at most one passport, and a passport one citizen.
Answer.
One-to-one
Common mistake.
Ignoring unique=True and saying one-to-many.
Finding the relationship: find the foreign keys, then two keys in a link table: many-to-many, then unique key: one-to-one, then otherwise: one-to-many
How to answer
| Step | Do this |
|---|---|
| 1 | Find every foreign key and the table that holds it. |
| 2 | The table holding the key is the many side. |
| 3 | A unique key makes it one-to-one. |
| 4 | Two keys in a linking table make many-to-many. |
Worked example: A link with its own data
Problem.
Students take many courses, and each enrolment has a grade. Where does the grade go?
Idea.
The grade belongs to the pair.
- One student has different grades in different courses, so it cannot sit in
student. - One course has many grades, so it cannot sit in
course. - It describes one student with one course.
- Put it in the linking table, written as its own model.
Answer.
In the linking (enrolment) table.
Common mistake.
Adding a grade column to student.
Ask of each side: can it have many of the other? Two yes answers mean a linking table.
db.ForeignKey('Assignment.id') fails: Flask-SQLAlchemy names the table assignment. And student_id = db.ForeignKey('student.id') without db.Column(...) is not a column at all, so the relationship finds no key.
Many-to-many in code. An association table holds pairs of keys. In Flask-SQLAlchemy you declare it with db.Table and point the relationship at it with secondary=. You then work with plain lists: a.courses = [web, db], and the pairs appear in the association table by themselves.
enroll = db.Table("enroll",
db.Column("student_id", db.Integer, db.ForeignKey("student.id")),
db.Column("course_id", db.Integer, db.ForeignKey("course.id")))
class Student(db.Model):
id = db.Column(db.Integer, primary_key=True)
courses = db.relationship("Course", secondary=enroll, backref="students")
# a.courses = [web, dbc]; b.courses = [web] -> enroll has 3 rows
The order of a relationship list is not guaranteed unless you ask for one (order_by= on the relationship or in the query). Compare lists as sets when the order does not matter.
The key sits on the many side; unique makes it one; two keys in a middle table make many-to-many.
7. The session: add, commit, update
Nothing is saved until you add it and commit.
what changes in the database and when
The question this lesson answers. You changed an object. Is it in the database yet? The session holds your changes until you commit.
s = Student(roll_number="M01", first_name="Yash", last_name="Raj")
db.session.add(s) # pending
db.session.commit() # written, s.s_id = 1
u = Student.query.filter_by(first_name="Yash").first()
u.first_name = "Ansh" # change the loaded object
db.session.commit() # UPDATE ... WHERE s_id = 1
Adding to the basket reserves nothing; paying at the counter does. add fills the basket and commit pays. Where the picture stops: if one item fails at the counter, nothing in the basket is bought.
Session calls
| Call | Does |
|---|---|
db.session.add(obj) / add_all([...]) | marks objects to insert |
db.session.commit() | writes everything pending and ends the transaction |
db.session.rollback() | throws away uncommitted changes |
db.session.delete(obj) | marks a row for deletion (commit to apply) |
Model.query.all() / .first() | list of all matches / one object or None |
Worked example: Insert in the right order
Problem.
Four shell sequences for inserting MaxScores(course_id='cs2002', high_score=86, term_year='Jan-2023').
Idea.
Keywords → add → commit.
- Positional arguments → TypeError.
db.commit()does not exist; it is db.session.commit().- commit then add: the add is never committed.
Answer.
create with keywords, db.session.add(s1), db.session.commit()
Common mistake.
Accepting commit-before-add because the same lines appear.
Worked example: Rename the first match
Problem.
members has the name Divya at ids 3, 4 and 8. The code does m = Member.query.filter_by(name="Divya").first(), sets m.name = "Dia", commits, then prints every row.
Idea.
first() returns one object (or None), never all matches.
first()gives one matching row; withoutorder_by, SQLite here returns id 3.- Only that object is changed and saved.
- Ids 4 and 8 still read Divya.
Answer.
Only id 3
Common mistake.
Renaming all three.
Check that the print line runs before tracing data: for emp1 in emp: print(first_name) raises NameError, because the loop variable is emp1.
When a commit fails. If commit() breaks a rule (say, a duplicate unique value), it raises IntegrityError and the session is left in a failed state: the next query raises PendingRollbackError. Call db.session.rollback(), and the session works again. db.session.get(Model, id) fetches one row by primary key, or None.
Worked example: Fetch by key
Problem.
Table U has one row with id 1, e = "a".
Idea.
get looks up by primary key and returns None when there is no such row.
- id 1 exists: its e is "a".
- id 9 does not: None.
Answer.
"a" and None
Common mistake.
Expecting an error for a missing id: get returns None.
A transaction is all or nothing. Everything changed since the last commit is saved together. If one change breaks a rule, the commit fails and rollback() undoes all of them. That is why a money transfer (take from one account, add to another) is safe in one commit: it can never half-happen.
Worked example: A transfer that breaks halfway
Problem.
Account 1 has 100, account 2 has 50; bal is NOT NULL. In one session: a.bal -= 30, then b.bal = None, then commit; on error, rollback.
Idea.
The NOT NULL rule fails the whole commit.
- The commit raises IntegrityError (bal cannot be NULL).
- rollback() undoes both changes, including the valid -30.
- Balances are still 100 and 50.
Answer.
100 and 50
Common mistake.
Expecting 70 and 50: the valid change is undone too.
Worked example: Seen before commit, gone after rollback
Problem.
A row has n = 1. In one session you set n = 9, query for rows with n == 9, then roll back. What does the query find, and what is n afterwards?
Idea.
A query in the same session first sends pending changes; rollback undoes them.
- The query flushes the change, so it finds the row.
- Rollback cancels the change.
Answer.
1 row; then n is 1.
Common mistake.
Expecting the query to find nothing before commit.
- Follow the object: created, added, committed. Without
committhe change is not saved. - After
first()check forNonebefore reading an attribute. - To update, change the attribute and commit; no second
addis needed for a fetched object.
add prepares, commit saves, rollback forgets.
Method for any exam question
| Step | Do this |
|---|---|
| 1 | List the changes since the last commit. |
| 2 | Find the next commit. |
| 3 | If it fails, none of those changes are saved. |
| 4 | Roll back before using the session again. |
8. relationship(), backref, objects and ids
Columns hold ids; relationships hold objects.
what the Python attributes of a relationship hold
The question this lesson answers. Should you hand a model a number or an object, and when does a new object get its number?
You may hand over the parent's id number, or hand over the parent object and let the library look up the number. The key column takes a number; the relationship takes an object.
class Channel(db.Model):
id = db.Column(db.Integer, primary_key=True)
videos = db.relationship("Video", backref="playlist")
class Video(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String)
channel = db.Column(db.Integer, db.ForeignKey("channel.id"))
Video(name="x", channel=1) # id in the column: works
Video(name="x", playlist=ch1) # object in the relationship: works
Video(name="x", channel=ch1) # fails at commit
Video(name="x", playlist=1) # AttributeError
backref vs back_populates
backref="x" | back_populates="x" | |
|---|---|---|
| Where written | one side only | both sides, each naming the other |
| Creates the other attribute | yes, automatically | no, you write it |
| Result | same pair of attributes | same pair of attributes |
Worked example: Which ways create the video?
Problem.
ch1 has id 1. Options: channel=ch1, channel=1, playlist=ch1, playlist=1.
Idea.
Column ← id, relationship ← object.
- channel=1 ✓.
- playlist=ch1 ✓ (fills channel with 1).
- The swapped two fail.
Answer.
channel=1 and playlist=ch1
Common mistake.
Choosing channel=ch1 because the column is named after the channel.
Worked example: The id that was not there yet
Problem.
a = Author(name="Ira"); b = Book(title="Tides", author_id=a.id); add both; commit; print Author.query.filter_by(name="Ira").first().books.
Idea.
a.id is None until the row is flushed or committed.
- When
bis built,a.idis None, sob.author_idis None. - The commit gives
aan id, butbstill points at no author. - The author's list of books is empty:
[]. - Committing
afirst, or buildingBook(title="Tides", author=a), links them.
Answer.
[]
Common mistake.
Assuming a.id is 1 as soon as a is created.
Life of a new object: created: id is None, then added to the session, then flushed: id assigned, then committed: saved
How to answer
| Step | Do this |
|---|---|
| 1 | Mark each attribute as a column or a relationship. |
| 2 | Give columns plain values such as an id. |
| 3 | Give relationships whole objects. |
| 4 | Remember that a new object gets its id only when saved. |
Worked example: An id that is not there yet
Problem.
u = User() and then p = Profile(user_id=u.id), before any flush or commit. What is stored in user_id?
Idea.
The database assigns the id when the row is written.
uhas not been written to the database.- So
u.idisNoneat that moment. user_idreceivesNone.- Setting the relationship, as in
Profile(user=u)where one is defined, avoids this.
Answer.
NULL, if the column allows it.
Common mistake.
Assuming the id exists as soon as the object is created.
If code copies .id before a commit or flush, suspect None.
Working through the list. You can link objects from either side. ch.videos.append(v) adds the video to the channel's list, and when the channel is added and committed, the video is saved too and its key column is filled. Deleting the parent by default does not delete the children: their foreign key is set to NULL.
What happens, step by step
| Code | Result |
|---|---|
ch.videos.append(v), add ch, commit | v.channel = 1, v.playlist is ch |
| delete ch, commit | the video stays, v.channel becomes NULL |
Worked example: Delete the channel
Problem.
Channel c has one video. db.session.delete(c), then commit (default relationship, no cascade option).
Idea.
Default behaviour: children are kept and unlinked.
- The channel row is deleted.
- SQLAlchemy sets the child's foreign key to NULL before deleting the parent.
- One video remains with channel NULL.
Answer.
1 video, channel None
Common mistake.
Expecting the video to be deleted too: that needs cascade="all, delete-orphan".
Columns take values, relationships take objects, ids appear on saving.
9. Queries: filter, filter_by, aggregates and dates
filter_by for name=value; filter for expressions, joined with & or and_.
writing conditions that really become SQL
The question this lesson answers. A query is a chain. What does each link do, and what type comes out at the end?
Asking a librarian: name the shelf, state the condition, then say whether you want one book, all of them or just the count.
filter_by vs filter
filter_by | filter | |
|---|---|---|
| Takes | keywords: status="PAID" | expressions: Order.amount > 500 |
| Operators | equality only | ==, !=, <, >, like, in_, … |
| Several conditions | filter_by(a=1, b=2) → AND | &, and_(), |, or_(), or chain |
| Wrong use | filter_by(Order.amount > 500) → TypeError | filter(status="PAID") → TypeError |
cond = (Order.status == "PAID") and (Order.amount > 500)
print(cond) # orders.status = :status_1 (amount is gone)
Order.query.filter(Order.status == "PAID").filter(Order.amount > 500) # AND
Order.query.filter((Order.status == "PAID") & (Order.amount > 500)) # AND
Order.query.filter(and_(Order.status == "PAID", Order.amount > 500)) # AND
Worked example: Cheapest order
Problem.
Order.amount holds 250, 90 and 410.
Idea.
Build the aggregate query, then run it with scalar().
db.session.query(func.min(Order.amount))only builds the SELECT..scalar()runs it and returns the single value.- Printing the query without
scalar()shows SQL text.
Answer.
print(db.session.query(func.min(Order.amount)).scalar())
Common mistake.
db.session.query.min(...): query is a function and has no min.
Worked example: Repairs over 7 days
Problem.
GlassRepair with Date columns broken_at and fixed_at. Option B filters in SQL with (fixed_at - broken_at) > 7.
Idea.
SQLite subtracts date text as numbers.
- Dates are stored as '2024-01-20'.
- Text to number stops at the first dash: 2024 - 2024 = 0.
- 0 > 7 is false for every row, so B returns [].
Answer.
No; load rows and use (r.fixed_at - r.broken_at).days in Python
Common mistake.
Trusting SQL date subtraction because it raises no error.
Model.query is a ready Query object: chain on it (Model.query.filter(...)), never call it. db.session.query(...) is the function you call with columns.
The query toolkit. Most questions combine a few pieces: order_by(col.desc()) to sort, limit(n) to keep the first n, in_([...]) for "one of these", like("s%") for patterns, and func.count, func.sum, func.avg with group_by for totals.
On five products (A: Biscuits 100, Chocolate 200; B: Shoes 500, Shirts 700; C: Pen 50)
| Query | Result |
|---|---|
P.query.order_by(P.cost.desc()).limit(2) | Shirts, Shoes |
P.query.filter(P.m.in_(["A", "C"])).count() | 3 |
db.session.query(P.m, func.count(P.id)).group_by(P.m) | (A, 2), (B, 2), (C, 1) |
P.query.filter(P.name.like("s%")).count() | 2 (Shoes, Shirts; LIKE ignores case) |
query(func.sum(P.cost)).scalar(), func.avg | 1550, 310.0 |
filter(P.cost > 150).order_by(P.name).first() | Chocolate |
Worked example: Count per maker
Problem.
Same five products.
Idea.
Group by the maker and count inside each group.
db.session.query(P.m, func.count(P.id)).group_by(P.m).order_by(P.m).all()- A has 2, B has 2, C has 1.
Answer.
[("A", 2), ("B", 2), ("C", 1)]
Common mistake.
Using P.query.count(), which counts all rows at once (5).
Joining in SQLAlchemy. Enrollment.query.join(Course) follows the foreign key, so you can filter on the other table's columns: which students are in the Web course? SQLAlchemy writes the JOIN ... ON for you from the ForeignKey.
web_students = (Enrollment.query
.join(Course)
.filter(Course.title == "Web")
.order_by(Enrollment.name)
.all())
# ['Asha', 'Ravi']
Worked example: Nothing matches
Problem.
No product is called Cup. What does P.query.filter_by(name="Cup").first().cost do?
Idea.
first() returns None when nothing matches.
- The filter matches no row.
first()givesNone.- Reading
.costfromNoneraisesAttributeError.
Answer.
It raises AttributeError.
Common mistake.
Expecting 0 or an empty list.
Subtracting dates in Python. A db.Date column arrives in Python as a date object. One date minus another is a timedelta, meaning a length of time. Its .days attribute is a whole number you can compare. timedelta(days=7) goes the other way: it builds a length of time from a number.
Days between two dates
from datetime import date, timedelta
gap = date(2024, 3, 12) - date(2024, 3, 1)
print(gap.days) # 11
print(gap.days > 7) # True
print(gap > timedelta(days=7)) # True
| Expression | Result |
|---|---|
gap.days > 7 | works: number against number |
gap > 7 | TypeError: a timedelta cannot be compared with a number |
timedelta(days=gap) | TypeError: days= needs a number, and gap is already a timedelta |
In SQLite, subtracting two date columns inside a query does not count days. Load the objects with .all(), then use (r.fixed_at - r.broken_at).days in a loop or list comprehension.
all() gives a list; first() gives an object or None.
Method for any exam question
| Step | Do this |
|---|---|
| 1 | Start with every row. |
| 2 | Apply each filter in turn. |
| 3 | Apply the ordering and limit. |
| 4 | Read the last call to know the type. |