MSK Institute LogoMSK.Institute
HomeCourses
Book Free Demo➔Sign In
Free Demo➔
MSK Institute LogoMSK.Institute

Leading computer training academy in Shikohabad for software engineering, Python, web development, and digital literacy.

ISO 9001:2015 Certified Center
Follow & Connect
4.9

Programs & Admissions

  • All CoursesCatalog
  • Learning PathsRoadmaps
  • Student ProjectsShowcase
  • Live Classes & ScheduleLive
  • Upcoming Batches
  • Campuses & LocationsHub
  • Verify Certificates
  • Book Free Demo Class

Resources & Tools

  • Free Online Mock TestsAll Tests
  • NIELIT CCC Mock TestFree
  • Course & Career FinderQuiz
  • Study Material Hub
  • All MSK ToolsHub
  • Keyboard ShortcutsNew
  • TypeQuest Speed LabTyping
  • MSK Code PlaygroundCode
  • Interactive Tutorials
  • Quick Cheatsheets

Institute & Contact

  • About MSK Institute
  • Careers & InternshipsHiring
  • Publications & Blogs
  • Gali No. 3, Near Gyan Jyoti Public School,
    Adarsh Nagar, Shikohabad, Uttar Pradesh 283135
  • +91 83930 42166
  • mskshikohabad@gmail.com
  • Hours:Mon – Sat: 8:00 AM – 7:00 PM | Sun: 10:00 AM – 2:00 PM
  • 4.9 ★(38 Google Reviews)
© 2026 MSK Institute. All rights reserved.•Privacy Policy•Terms of Service•Disclaimer•Contact Us

Shikohabad's Leading Computer & Coding Academy

Home
Courses
Live
Material
Migrations & ORM Queries0%
Study Materials
Django for Backend DevelopmentProgress 0%
1.1Installing Django & Environment Setup1.2Django Project Structure1.3Creating First Django App
2.1Creating Models2.2Field Types & Relationships2.3Migrations & ORM Queries
HomeTutorialsDjango for Backend DevelopmentMigrations & ORM Queries
Django Admin Site

Migrations & ORM Queries

Beginner12 min read•Updated: 2026-11-18•By Er. Sumit Kumar (MSK Institute)
Study MaterialsCheatsheet

Django's Object-Relational Mapper (ORM) translates high-level Python method calls into optimized SQL queries. The ORM's QuerySet API is lazy: queries are not executed against the database until the data is explicitly evaluated. Mastering QuerySet filtering, chaining, aggregations, and migration workflows ensures both developer productivity and database performance.


1. The QuerySet Execution Lifecycle

A QuerySet represents a collection of database rows. Creating a QuerySet does not touch the database:

1# No SQL is executed here! (Lazy evaluation)
2published_articles = Article.objects.filter(status="published").order_by("-created_at")
3 
4# Database query executes ONLY when QuerySet is evaluated:
5for article in published_articles: # 1. Iteration
6 print(article.title)
7 
8article_list = list(published_articles) # 2. Converting to list
9count = published_articles.count() # 3. Aggregation (executes SELECT COUNT(*))
10first = published_articles.first() # 4. Slicing / Indexing (LIMIT 1)
11exists = published_articles.exists() # 5. Boolean check (EXISTS query)

2. QuerySet Filtering with Field Lookups

Django uses double-underscore (__) notation for SQL operators:

1# Exact match
2Article.objects.filter(status__exact="published")
3 
4# Case-insensitive contains (SQL LIKE '%django%')
5Article.objects.filter(title__icontains="django")
6 
7# Greater than or equal (SQL >=)
8Article.objects.filter(view_count__gte=1000)
9 
10# SQL IN operator
11Article.objects.filter(category__slug__in=["python", "django", "backend"])
12 
13# Date filters
14Article.objects.filter(created_at__year=2026)
15 
16# Spanning relationships across foreign keys:
17# Find all articles written by user with username 'dr_sumit'
18Article.objects.filter(author__username="dr_sumit")

3. Complex Queries with Q Objects and F Expressions

Logical OR Queries with Q

Standard .filter(a=1, b=2) combines clauses with SQL AND. To write SQL OR queries, use Q objects:

1from django.db.models import Q
2 
3# SQL: WHERE status = 'published' OR is_featured = true
4query = Article.objects.filter(Q(status="published") | Q(is_featured=True))
5 
6# SQL: WHERE status = 'published' AND NOT author_id = 5
7query = Article.objects.filter(Q(status="published") & ~Q(author__id=5))

Database Field Operations with F Expressions

F expressions reference database column values directly in SQL without loading them into Python memory:

1from django.db.models import F
2 
3# Atomically increment view_count in database (race-condition free!)
4Article.objects.filter(id=1).update(view_count=F("view_count") + 1)

4. Advanced Migration Commands

1# Display status of all applied/unapplied migrations
2python manage.py showmigrations
3 
4# Rollback an app to a specific previous migration
5python manage.py migrate articles 0002
6 
7# Rollback an app completely
8python manage.py migrate articles zero

Interactive Quiz• Knowledge Check

Practice Quiz

Question 1
What does it mean that Django QuerySets are "lazy"?
Question 2
How do you construct an SQL OR condition in Django ORM?
Question 3
Why is using F('view_count') + 1 superior to article.view_count += 1 followed by save()?
Question 4
Which method checks if matching records exist with maximum efficiency?
Question 5
What command lists all migrations across all apps along with an [X] indicating whether they have been applied?
Next Lesson

Django Admin Site

Continue learning with hands-on practice, examples, and exercises in the upcoming topic.

Related Lessons

Previous LessonNext Lesson
Field Types & RelationshipsDjango Admin Site

Practice Quiz

Test your understanding of this lesson with 5 questions. Each question has one correct answer.

Mentor-Led Practical Training

Master Django for Backend Development with Hands-On Projects

Practice in live mentor-led sessions with real projects, mock tests, and verifiable certification at MSK Institute.

View Full CourseBook Free Demo
PreviousNext
PreviousPrevNext