Skip to content

Introduction to ORMs

An ORM (Object-Relational Mapper) lets you work with a SQL database using Python objects.

Instead of writing SQL like:

sql
SELECT id, username FROM users WHERE id = 1;

You write Python like:

python
user = User.query.get(1)
diagram the N+1 query problem, and the option that fixes it mermaid
A relationship is lazy by default: the list of children is not fetched until you touch it. Loop over parents and touch each list, and you have issued one query for the parents plus one per parent. Asking for the relationship up front turns the whole thing into a single join.
  • Python classes represent tables
  • Instances represent rows
  • Methods/queries generate SQL
  • Safe parameter binding (helps prevent SQL injection)
  • Relationships (foreign keys) become Python attributes

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

In Flask apps, a common stack is:

  • Flask-SQLAlchemy: app integration + db helper
  • SQLAlchemy: the ORM engine

You’ll define models and query them, but it helps to keep SQL fundamentals in mind.

pch.coffeeTagline

pch.coffeeCta

pch.feedbackHeading

pch.feedbackSubheading