← Back to all tutorials

The Django ORM

Query the database using Python — use the Django ORM to create, read, filter, and delete records without writing SQL.

The Django ORM

The Object-Relational Mapper (ORM) lets you interact with your database using Python instead of SQL. Each model has a objects manager that provides query methods.

The Django Shell

python manage.py shell

The shell gives you a Python REPL with Django loaded, perfect for testing queries.

Creating Records

from articles.models import Article

# Method 1: Create and save in two steps
article = Article(title='My First Post', slug='my-first-post', body='Hello world!')
article.save()

# Method 2: Create and save in one step
article = Article.objects.create(
    title='Second Post',
    slug='second-post',
    body='Another article.'
)

Reading Records

# Get all articles
articles = Article.objects.all()

# Get a single article
article = Article.objects.get(id=1)
article = Article.objects.get(slug='my-first-post')

# Filter articles
recent = Article.objects.filter(date__year=2025)
long_titles = Article.objects.filter(title__contains='Django')

# Order articles
ordered = Article.objects.all().order_by('-date')  # Newest first
ordered = Article.objects.all().order_by('title')   # A to Z

Common Query Methods

MethodReturnsUse Case
all()QuerySet of all recordsListing all items
get()Single object (or error)Finding one specific item
filter()QuerySet of matching recordsSearching with conditions
exclude()QuerySet excluding matchesInverse filtering
order_by()Ordered QuerySetSorting results
first()First record or NoneGetting the first match
count()IntegerCounting records

Updating and Deleting

# Update
article = Article.objects.get(id=1)
article.title = 'Updated Title'
article.save()

# Delete
article = Article.objects.get(id=1)
article.delete()

Using in Views

# articles/views.py
from .models import Article

def article_list(request):
    articles = Article.objects.all().order_by('-date')
    return render(request, 'articles/article_list.html', {
        'articles': articles
    })

Key Takeaways

  • The ORM lets you query the database with Python — no SQL needed
  • Model.objects is the entry point for all queries
  • all(), get(), filter(), and order_by() are the most common methods
  • Pass QuerySets to templates through the context dictionary