Skip to content

django-orm

Use when working with Django models, fields, querysets, migrations, or database relationships. Also use when optimizing N+1 queries, writing complex lookups with Q/F objects, using aggregations, managing transactions, or working with GeneratedField in Django 5.x.

ModelSource
sonnetpack: python
Full Reference

Django ORM provides a Python API over SQL databases. The QuerySet is lazy — it only hits the database when evaluated. Django 5.0 added GeneratedField (database-generated columns). Django 4.1+ adds a-prefixed async variants for all blocking ORM methods.

ItemValue
Django version5.2 (GeneratedField in 5.0, async ORM in 4.1)
QuerySet is lazyEvaluates on iteration, slicing, or explicit calls (list(), count())
N+1 fix (FK/O2O)select_related("field") — single JOIN
N+1 fix (M2M/reverse FK)prefetch_related("field") — separate optimized query
Async iterateasync for obj in qs.aiterator()
Atomic writeswith transaction.atomic():
I want to…File
Define models, fields, constraints, indexes, and GeneratedFieldreference/model-design.md
Write QuerySet filters, annotations, aggregations, Q/F objects, and subqueriesreference/querysets.md
Set up ForeignKey, ManyToMany, OneToOne, and Prefetch objectsreference/relationships.md
Create, run, and write data migrationsreference/migrations.md
Use atomic transactions, savepoints, and on_commit hooksreference/transactions-async.md

Usage: Read the reference file matching your current task from the index above. Each file is self-contained with code examples and inline gotchas.


┏━ 🗄 django-orm ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓ ┃ Django ORM — models, querysets, migrations, and relationships ┃ ┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛