Back to Study Material Python

Django ORM

The Django ORM (Object-Relational Mapper) translates Python code into SQL queries, letting you interact with a database without writing a single SQL statem...

Django ORM

Querying Databases with the Django ORM

The Django ORM (Object-Relational Mapper) translates Python code into SQL queries, letting you interact with a database without writing a single SQL statement. It supports SQLite, PostgreSQL, MySQL, MariaDB, and Oracle.

Every Django model has a Manager (accessed via ModelName.objects) that provides a QuerySet API. QuerySets are lazy — they hit the database only when you evaluate them (iterate, slice, or call list()).

Common QuerySet operations: # Retrieve all articles articles = Article.objects.all()

# Filter recent = Article.objects.filter(published_at__year=2024) django_posts = Article.objects.filter(title__icontains='django')

# Exclude not_draft = Article.objects.exclude(status='draft')

# Order latest = Article.objects.order_by('-published_at')[:10] # last 10

# Get single object (raises DoesNotExist if not found) article = Article.objects.get(pk=1)

# get_or_create returns (object, created_boolean) obj, created = Article.objects.get_or_create(title='My Post', defaults={'content': '...'})

Field lookups use double underscores: exact, iexact, contains, icontains, startswith, in, gt, gte, lt, lte, range, isnull, date, year, month.

Relationships: # ForeignKey — access related object author_name = article.author.username

# Reverse relation — all articles by a user user_articles = user.article_set.all() # or use related_name='articles' in the model and: user.articles.all()

# select_related prefetches ForeignKey in one SQL JOIN (for single objects): articles = Article.objects.select_related('author').all()

# prefetch_related prefetches ManyToMany or reverse FK (uses separate query): articles = Article.objects.prefetch_related('tags').all()

Aggregation and annotation: from django.db.models import Count, Avg Article.objects.aggregate(total=Count('id')) Author.objects.annotate(article_count=Count('article'))

Raw SQL when you need it: results = Article.objects.raw('SELECT * FROM blog_article WHERE status = %s', ['published'])

Practical tip: Use select_related for ForeignKey and OneToOne fields, and prefetch_related for ManyToMany and reverse ForeignKey relations. Forgetting these causes N+1 query problems that destroy performance.

Exam tip: Q objects allow complex OR / AND / NOT queries: Article.objects.filter(Q(title__icontains='python') | Q(content__icontains='python')). This is something interviewers often test.