ORMs

What is an ORM

When building applications with Python and relational databases like PostgreSQL or MySQL, developers often face a challenge: how to write clean, readable code while still working efficiently with database data. That's where ORMs come in.

It's a technique that allows you to interact with a database using objects instead of raw SQL queries.

  • You define classes in Python that represent your database tables.
  • Each object (or instance) of a class corresponds to a row in the table.
  • Each attribute of the object maps to a column in the table.

The ORM library handles the conversion (or "mapping") between your Python objects and the underlying relational database structure. This allows you to perform database operations using Python syntax without having to manually write SQL statements.

Using an ORM provides several benefits:

  • Readability & Maintainability: Writing queries in Python feels more natural and readable than writing raw SQL.
  • Fewer Errors: ORMs help avoid typos in table or column names and reduce the risk of SQL injection when used correctly.
  • Portability: You can switch between different types of databases (e.g., SQLite to PostgreSQL) with minimal code changes.
  • Rapid Development: ORMs are faster to work with, especially in early development stages or when prototyping.

Without an ORM:

SELECT * FROM users WHERE id = 1;

With an ORM in Python:

user = User.objects.get(id=1)

ORM Libraries

The Django ORM provides simple syntax and integrates deeply with Django's admin, forms, and views but it cannot be used outside of Django projects.

  • Tightly coupled with the Django web framework.
  • Provides a high-level abstraction to define models, querysets, and perform migrations.
  • Easy to get started with for web apps.

SQLAlchemy is a standalone ORM that can be used in any Python project (web or non-web). And offers three levels of abstraction:

  • Core layer: write SQL-like code using Python
  • ORM layer: map classes to tables
  • Full automation layer: manage sessions, relationships, and migrations

This is very powerful and flexible, raw SQL can be used it needed, and works outside of any specific framework but it can be more complex to learn.