ORM Basics & QuerySet API
Django's ORM (Object-Relational Mapping) lets you query and manipulate the database using Python instead of SQL. QuerySets are lazy — they don't hit the database until you evaluate them. This enables efficient query chaining.
20 min•By Priygop Team•Updated 2026
QuerySet Methods
- Model.objects.all() — Get all records
- Model.objects.get(pk=1) — Get single record (raises DoesNotExist)
- Model.objects.filter(field=value) — Filter records
- Model.objects.exclude(field=value) — Exclude records
- Model.objects.order_by('-field') — Sort results
- Model.objects.count() — Count records
- Model.objects.first() / .last() — First/last record
- Model.objects.values('field') — Return dictionaries
- Model.objects.exists() — Check if any records exist
- QuerySets are LAZY — chained, not executed until evaluated
ORM Queries
ORM Queries
# Django Shell: python manage.py shell
# from blog.models import Post
# Create
# post = Post.objects.create(title='Hello', content='World')
# Read all
# posts = Post.objects.all()
# Filter — WHERE clause
# published = Post.objects.filter(published=True)
# recent = Post.objects.filter(created_at__year=2026)
# Lookups (double underscore)
# Post.objects.filter(title__contains='django') # LIKE '%django%'
# Post.objects.filter(title__icontains='django') # Case-insensitive
# Post.objects.filter(views_count__gte=100) # >= 100
# Post.objects.filter(views_count__range=(10, 100)) # BETWEEN
# Post.objects.filter(category__name='Python') # Join query
# Post.objects.filter(created_at__date=date.today()) # Date lookup
# Chaining (lazy — one SQL query)
# posts = Post.objects.filter(
# published=True
# ).exclude(
# author__username='admin'
# ).order_by('-created_at')[:10]
# Aggregation
# from django.db.models import Count, Avg
# Post.objects.aggregate(
# total=Count('id'),
# avg_views=Avg('views_count')
# )Tip
Tip
Use select_related for ForeignKey joins and prefetch_related for ManyToMany. Both eliminate N+1 query problems.
Diagram
Loading diagram…
QuerySets are LAZY — no DB hit until evaluated.
Common Mistake
Warning
Not using select_related in views with related objects. Each post.author in templates triggers a separate query without it.
Practice Task
Note
(1) Use django-debug-toolbar to count queries. (2) Add select_related and compare. (3) Use prefetch_related for M2M.
Quick Quiz
Key Takeaways
- Django's ORM (Object-Relational Mapping) lets you query and manipulate the database using Python instead of SQL.
- Model.objects.all() — Get all records
- Model.objects.get(pk=1) — Get single record (raises DoesNotExist)
- Model.objects.filter(field=value) — Filter records