Skip to main content

Chapter 1: ORM Fundamentals

Learning Objectives

By the end of this chapter, you will understand:
  • What an ORM is
  • Why we need an ORM
  • Database World vs Python World
  • How SQLAlchemy works
  • The mapping between database tables and Python objects
  • The complete lifecycle of an ORM operation

The Problem

Suppose we have a table named students.
To insert a student:
To retrieve students:
To update a student:
To delete a student:
As applications grow, writing SQL everywhere becomes repetitive and difficult to maintain.

What is an ORM?

ORM (Object Relational Mapper) is a library that converts:
  • Python Objects ⇄ Database Rows
Instead of writing SQL, we work with Python objects. Instead of this:
we simply write:
The ORM automatically generates the SQL.

Why Do We Need an ORM?

Without an ORM:
With an ORM:
SQLAlchemy acts as a translator between Python and the database.

Database World vs Python World

This is the most important concept to remember.

Database World

The database understands:
  • Tables
  • Rows
  • Columns
  • SQL
Example:

Python World

Python understands:
  • Classes
  • Objects
  • Attributes
Example:
The ORM connects these two worlds.

Object Mapping

The ORM maps database concepts to Python concepts. Example:

CRUD Through an ORM

Create

Instead of SQL:
we create an object.

Read

Instead of SQL:
we ask for Python objects.

Update

Instead of SQL:
we modify the object.

Delete

Instead of SQL:
we remove the object.

Complete Flow

As developers, we mostly work with Python objects. SQLAlchemy handles the SQL generation.

SQL vs SQLAlchemy

Mental Model

Never think:
“I’m writing SQLAlchemy.”
Instead think:
“I’m describing the data I want.”
Example:
Read it as:
Select students.
Another example:
Read it as:
Select students where age is greater than 18.
The API becomes much easier when you read it like English.

Key Takeaways

  • ORM stands for Object Relational Mapper.
  • SQLAlchemy translates Python objects into SQL.
  • The database works with tables, rows, and columns.
  • Python works with classes, objects, and attributes.
  • SQLAlchemy bridges these two worlds.
  • Think in terms of Python objects rather than SQL statements.

Quick Revision

  • ORM = Python Objects ⇄ Database Rows
  • Table ⇄ Class
  • Row ⇄ Object
  • Column ⇄ Attribute
  • SQLAlchemy is a translator between Python and SQL.
  • Describe the data you want instead of thinking about SQL syntax.