ORM
An object-relational mapper (ORM) maps classes and instances to tables and rows so you work with Order objects instead of SELECT strings. SQLAlchemy and the Django ORM are the two you will meet first.
Detailed Explanation
A row becomes an instance. A foreign key becomes a relationship. Saving is session.add / session.commit or order.save(). The ORM writes the SQL. That is faster to write for CRUD and easier to get slightly wrong for reports.
The identity map (SQLAlchemy) or the Django instance you just saved is not a cache of the database. Another request has its own objects. Concurrent updates need transactions and often a version column.
Queries are lazy. Order.objects.filter(open=True) is not SQL until you iterate. select(Order) is not SQL until execute. Chaining filters builds a query object. A forgotten .all() in a log line can trigger a query. A property that touches a relation triggers another.
ORMs hide SQL injection if you use the expression API. They do not hide it if you pass raw strings or extra(where=[user_input]). The same parameter rule applies.
When the ORM gets in the way — window functions, upserts, CTEs — drop to raw SQL or Core and map the rows yourself. An ORM is a tool, not a rule that every query must be objects.
Testing: an in-memory sqlite database works until you use Postgres-specific types. Then you need a test container or a stub repository. Do not mock the ORM session with twenty MagicMocks if you can run sqlite.
Django's ORM is tied to the framework and migrations. SQLAlchemy is a library you bring to Flask or FastAPI. Peewee and Tortoise occupy smaller niches. The ideas transfer: models, querysets, sessions, lazy relations.
Code Examples
# Django-shaped sketch
# class Order(models.Model):
# cents = models.IntegerField()
#
# Order.objects.filter(cents__gte=1000)# The cost of laziness: each print can be a query.
class Line:
def __init__(self, sku: str):
self.sku = sku
class Order:
def __init__(self, lines: list[Line]):
self._lines = lines
@property
def lines(self) -> list[Line]:
return self._lines # imagine this ran SELECT
order = Order([Line("A-1"), Line("B-2")])
print([line.sku for line in order.lines])Common Gotchas
Treating a queryset as data in a boolean test
`if qs:` may run a query. Use `if qs.exists():`.
Building SQL with strings on the ORM
`raw(f"...")` is still injection. Bind parameters.
Lazy relations in a serializer loop
N+1. `select_related` / `prefetch_related` / `selectinload`.
`save()` does not mean others see it
no commit, no visibility. Know your session's autoflush and autocommit settings.