๐Ÿ“ Python

What is an ORM

P
Author
PyLand Team
๐Ÿ“…
Published
30.06.2026
โฑ๏ธ
Reading time
1 min
๐Ÿ‘๏ธ
Views
362
๐ŸŒฟ
Level
Medium

ORM (Object-Relational Mapping) is a technology that lets you work with a database through Python objects instead of writing raw SQL.

Without ORM (raw SQL)

import sqlite3

conn = sqlite3.connect('db.sqlite3')
cursor = conn.cursor()

cursor.execute("INSERT INTO tasks (title, status) VALUES (?, ?)", ('Task', 'todo'))
cursor.execute("SELECT * FROM tasks WHERE status = ?", ('todo',))
rows = cursor.fetchall()

With ORM (Django ORM)

from tasks.models import Task

# Create
task = Task.objects.create(title='Task', status='todo')

# Read
tasks = Task.objects.filter(status='todo')

# Update
task.status = 'done'
task.save()

# Delete
task.delete()

Advantages of ORM

  • Security โ€” protection against SQL injection
  • Readability โ€” Python code instead of SQL strings
  • Portability โ€” the same code works with SQLite, PostgreSQL, and MySQL
  • Migrations โ€” automatic schema updates

How ORM generates SQL

# Python
Task.objects.filter(status='todo', priority__gte=2)

# Generates SQL:
# SELECT * FROM tasks WHERE status = 'todo' AND priority >= 2

You can inspect the generated SQL:

qs = Task.objects.filter(status='todo')
print(qs.query)
# SELECT "tasks_task"."id", ... FROM "tasks_task" WHERE "tasks_task"."status" = 'todo'
ORM Used with
Django ORM Django
SQLAlchemy Flask, FastAPI, standalone
SQLModel FastAPI (built on SQLAlchemy)
Peewee Lightweight projects
Tortoise ORM Async Python

When ORM is not enough

For complex analytical queries, raw SQL is sometimes more efficient:

from django.db import connection

with connection.cursor() as cursor:
    cursor.execute("SELECT date_trunc('month', created_at), COUNT(*) FROM tasks GROUP BY 1")
    rows = cursor.fetchall()

Your reaction to the article

๐Ÿ’ฌ Comments (0)

๐Ÿ” Sign in to leave a comment
๐Ÿšช Login
๐Ÿ’ญ

No comments yet

Be the first to share your opinion about this article!

๐Ÿ”— Similar

Similar articles

Continue learning with these materials

๐Ÿ“

JSON: Persisting Data

Goal: Learn to save and load data in JSON format.

๐Ÿ“… 03.04.2026 ๐Ÿ‘๏ธ 466
๐Ÿ“

CSV: Working with Tables

CSV (Comma-Separated Values) is a text format for storing tabular data. It opens in Excel...

๐Ÿ“… 03.04.2026 ๐Ÿ‘๏ธ 434
๐Ÿ“

OOP: Program Like a World Builder ๐ŸŒ

Imagine: you're building a zombie-apocalypse game. You need zombies, humans, weapons. Every zombie has a...

๐Ÿ“… 03.04.2026 ๐Ÿ‘๏ธ 413

Did you like the article?

Subscribe to our updates and be the first to receive new articles. Grow with PyLand!