CRUD - Read Record
Reading records is about querying the database.
flowchart LR
subgraph Create
C1["obj = Model(...)"] --> C2["db.session.add(obj)"] --> C3["commit()"]
end
subgraph Read
R1["Model.query.get / filter_by"] --> R2["objects, already in the session"]
end
subgraph Update
U1["obj = query...first()"] --> U2["obj.field = new_value"] --> U3["commit()"]
end
subgraph Delete
D1["obj = query...first()"] --> D2["db.session.delete(obj)"] --> D3["commit()"]
end
R2 -.->|"no add() needed -- it is already tracked"| U2
Basic lookups
Section titled “Basic lookups”user = User.query.get(1)- Returns the user with primary key
1orNone
Filter by column
Section titled “Filter by column”user = User.query.filter_by(username="ravi").first()first()returns one row orNone
Get all rows
Section titled “Get all rows”users = User.query.all()Ordering
Section titled “Ordering”users = User.query.order_by(User.username.asc()).all()Common pattern: 404 if not found
Section titled “Common pattern: 404 if not found”In routes, you often want “not found” to return a 404.
Flask-SQLAlchemy provides:
user = User.query.get_or_404(user_id)That’s very convenient for web apps.
Performance note
Section titled “Performance note”all() loads everything into memory.
For very large tables, use pagination (limit/offset) or streaming approaches.
pch.coffeeTagline
pch.coffeeCtapch.feedbackHeading
pch.feedbackSubheading