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 namedstudents.
What is an ORM?
ORM (Object Relational Mapper) is a library that converts:- Python Objects ⇄ Database Rows
Why Do We Need an ORM?
Without an ORM:Database World vs Python World
This is the most important concept to remember.Database World
The database understands:- Tables
- Rows
- Columns
- SQL
Python World
Python understands:- Classes
- Objects
- Attributes
Object Mapping
The ORM maps database concepts to Python concepts.
Example:
CRUD Through an ORM
Create
Instead of SQL:Read
Instead of SQL:Update
Instead of SQL:Delete
Instead of SQL:Complete Flow
SQL vs SQLAlchemy
Mental Model
Never think:“I’m writing SQLAlchemy.”Instead think:
“I’m describing the data I want.”Example:
Select students.Another example:
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.