ORM Basics
ORM Basics
So far, you have worked with databases using SQL queries.
Example:
SELECT * FROM users;
SQL is powerful and important.
But in Python projects, developers often use another approach called an ORM.
What Is an ORM?
ORM stands for Object-Relational Mapping.
An ORM lets you work with database tables using Python classes and objects instead of writing raw SQL for everything.
It maps:
- database table → Python class
- row → Python object
- column → object attribute
Why ORMs Matter
ORMs help you:
- write more Python and less SQL
- organize database code
- reuse models
- work well with OOP
- improve readability
- support multiple databases
SQL vs ORM Example
SQL
SELECT * FROM users WHERE id = 1;
ORM Style
user = User.get(1)
Same goal, different style.
Table to Class Example
Database table:
users
id | name | age
ORM model:
class User:
id
name
age
One row becomes one object.
Example Concept
Instead of:
INSERT INTO users (name, age)
VALUES ('Maya', 30);
You might do:
user = User(name="Maya", age=30)
user.save()
Reading Data
Instead of:
SELECT * FROM users;
You might do:
users = User.all()
Updating Data
Instead of:
UPDATE users SET age = 31 WHERE id = 1;
You might do:
user.age = 31
user.save()
Deleting Data
Instead of:
DELETE FROM users WHERE id = 1;
You might do:
user.delete()
Why ORMs Are Popular
Large projects often have many tables.
Using classes fits naturally with Python OOP.
Example:
class Product:
pass
class Order:
pass
class Customer:
pass
This can be easier to manage than many SQL strings everywhere.
Important Note
ORMs do not replace SQL knowledge.
Good developers still understand SQL.
ORMs are built on database concepts.
Benefits of ORMs
- cleaner code
- reusable models
- easier maintenance
- less repeated SQL
- database abstraction
Trade-Offs
Sometimes raw SQL is better for:
- very complex queries
- performance tuning
- database-specific features
Best developers know both.
Popular Python ORMs
- SQLAlchemy
- Django ORM
- Peewee
- Tortoise ORM
Next lesson focuses on SQLAlchemy.
Code Along
Imagine a books table.
Write the Python class name and 3 attributes an ORM model might use.
Example:
class Book:
id
title
year
Mini Challenge
Convert these SQL ideas into ORM-style ideas:
- Insert user named Tom
- Get all products
- Delete order id 5
Write pseudocode only.
Example:
user = User(name="Tom")
Real World Use Case
Modern web apps often use ORMs to manage users, products, orders, reports, and business data.
Quiz
- What does ORM stand for?
- What does a database row become in ORM?
- Why do developers use ORMs?
- Should you still learn SQL?
Assignment
Choose one table idea and design its Python ORM model with 4 attributes.
Summary
You learned how ORMs let Python programs work with databases using classes and objects instead of only raw SQL.