Episode 8 of 32
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
| Method | Returns | Use Case |
|---|---|---|
all() | QuerySet of all records | Listing all items |
get() | Single object (or error) | Finding one specific item |
filter() | QuerySet of matching records | Searching with conditions |
exclude() | QuerySet excluding matches | Inverse filtering |
order_by() | Ordered QuerySet | Sorting results |
first() | First record or None | Getting the first match |
count() | Integer | Counting 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.objectsis the entry point for all queriesall(),get(),filter(), andorder_by()are the most common methods- Pass QuerySets to templates through the context dictionary