Introduction to ORMs
An ORM (Object-Relational Mapper) lets you work with a SQL database using Python objects.
Instead of writing SQL like:
SELECT id, username FROM users WHERE id = 1;You write Python like:
user = User.query.get(1)flowchart TD A["Author.query.all()"] --> B["1 SELECT for the authors"] B --> C["for author in authors:"] C --> D["author.books -- not loaded yet"] D --> E["a SELECT per author"] E --> F["3 authors -> 4 SELECTs total"] G["Author.query.options(joinedload(Author.books))"] --> H["1 SELECT with a LEFT OUTER JOIN"] H --> I["the collections arrive already populated"] I --> J["3 authors -> 1 SELECT"]
What an ORM gives you
Section titled “What an ORM gives you”- Python classes represent tables
- Instances represent rows
- Methods/queries generate SQL
- Safe parameter binding (helps prevent SQL injection)
- Relationships (foreign keys) become Python attributes
Tradeoffs
Section titled “Tradeoffs”ORMS are great, but not magic:
- You still need to understand SQL concepts (indexes, joins, transactions)
- Bad queries are still possible (N+1 query problem)
- For complex reporting, raw SQL can be clearer
Flask + SQLAlchemy
Section titled “Flask + SQLAlchemy”In Flask apps, a common stack is:
- Flask-SQLAlchemy: app integration +
dbhelper - SQLAlchemy: the ORM engine
You’ll define models and query them, but it helps to keep SQL fundamentals in mind.
🧪 Try It Yourself
Section titled “🧪 Try It Yourself”Exercise 1 – Create a Flask App
Section titled “Exercise 1 – Create a Flask App”Exercise 2 – Dynamic Route
Section titled “Exercise 2 – Dynamic Route”Exercise 3 – Return JSON
Section titled “Exercise 3 – Return JSON”pch.coffeeTagline
pch.coffeeCtapch.feedbackHeading
pch.feedbackSubheading