Django ORM & Database Queries

🐍 DjangoLesson 6Intermediate

Django features a powerful Object-Relational Mapper (ORM) that lets you interact with databases using Python objects instead of writing raw SQL queries.

1 Querying API Basics
Python — ORM Queries
# Fetch all records
posts = Post.objects.all()

# Filter records (WHERE condition)
published_posts = Post.objects.filter(is_published=True)

# Exact lookups and field double-underscores (__) lookup syntax
tech_posts = Post.objects.filter(category__name__iexact="technology")

# Fetch a single object
try:
    post = Post.objects.get(id=42)
except Post.DoesNotExist:
    post = None

# Complex AND/OR lookups using Q objects
from django.db.models import Q
query = Post.objects.filter(Q(title__contains="python") | Q(content__contains="tutorial"))
2 Optimization: select_related & prefetch_related
Python — Performance Queries
# select_related (SQL JOIN for ForeignKey relations)
posts = Post.objects.select_related("author", "category").all()

# prefetch_related (Separate query lookup for ManyToMany / Reverse ForeignKey relations)
categories = Category.objects.prefetch_related("posts").all()
3 Code Challenge
Challenge: Write a query retrieving all published posts authored by a user named "balaji" created in the year 2026. Optimize the query using select_related to avoid N+1 issues.