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:

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

You write Python like:

user = User.query.get(1)
user = User.query.get(1)

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

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

In Flask apps, a common stack is:

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

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

๐Ÿงช Try It Yourself

Exercise 1 โ€“ Create a Flask App

Exercise 2 โ€“ Dynamic Route

Exercise 3 โ€“ Return JSON

If this helped you, consider buying me a coffee โ˜•

Buy me a coffee

Was this page helpful?

Let us know how we did