Django ORM Queries
6 min read Quiz at the end
Query with get, filter, exclude, annotate, aggregate, select_related, and prefetch_related.
Django ORM
# Create
post = Post.objects.create(title="Hello", slug="hello", body="World", author=user)
# Read
post = Post.objects.get(id=1) # raises DoesNotExist if missing
post = Post.objects.get(slug="hello")
posts = Post.objects.all()
posts = Post.objects.filter(is_draft=False, author=user)
posts = Post.objects.exclude(is_draft=True)
post = Post.objects.filter(slug="hello").first() # or None
# Filter operators
Post.objects.filter(title__icontains="django") # case-insensitive
Post.objects.filter(created_at__date=date.today())
Post.objects.filter(views__gte=100)
Post.objects.filter(author__in=users)
# Update
Post.objects.filter(author=user).update(is_draft=False)
# Delete
Post.objects.filter(is_draft=True).delete()
# Aggregates
from django.db.models import Count, Avg, Sum
Post.objects.aggregate(total=Count("id"), avg_views=Avg("views"))
# Select related (prevent N+1)
Post.objects.select_related("author").prefetch_related("tags").all()
Topic Quiz · 3 questions
Test your understanding before moving on
1. What does Post.objects.get() do when no record found?
💡 get() raises Model.DoesNotExist if no matching record.
2. Which method prevents N+1 for ForeignKey relations?
💡 select_related() performs a SQL JOIN for ForeignKey — eliminates N+1 for single relations.
3. What does filter() return?
💡 filter() returns a QuerySet which is lazy — SQL runs only when evaluated.