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;
sql
SELECT id, username FROM users WHERE id = 1;

You write Python like:

python
user = User.query.get(1)
python
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