Django ORM

Now that we have models and migrations set up, it is time to learn how to actually read, create, update, and delete data in the database. Django provides a powerful tool called the ORM (Object-Relational Mapper) that lets you interact with your database using simple Python code instead of writing SQL queries.

What is the Django ORM?

ORM stands for Object-Relational Mapper. It is a translator that converts your Python instructions into SQL database commands and vice versa. You write Python — Django handles the SQL behind the scenes.

Example: Imagine you want to call someone in Japan. Instead of learning Japanese, you hire an interpreter (ORM). You speak in English (Python), the interpreter translates it to Japanese (SQL), the person in Japan responds in Japanese, and the interpreter translates back to English. You never need to learn Japanese at all.

The Django Shell — Testing Queries Live

The best way to practice ORM queries is through the Django shell. It is an interactive Python console with your Django project loaded:


python manage.py shell

Now you can import your models and try queries directly:


from school.models import Student

Creating Records

Method 1 — Using create()


Student.objects.create(name="Rahul Sharma", age=15, grade="10th", email="rahul@school.com")

Method 2 — Creating an object and saving manually


student = Student(name="Priya Singh", age=14, grade="9th", email="priya@school.com")
student.save()
Example: Using create() is like filling an admission form and submitting it in one go. The two-step method (create object, then save) is like filling the form first, reviewing it, and then submitting.

Reading Records

Get all records


all_students = Student.objects.all()

This returns a QuerySet — a list-like object containing all student records from the database.

Get a single record by ID


student = Student.objects.get(id=1)
print(student.name)   # Output: Rahul Sharma

Important: get() raises an error if no record or more than one record is found. Use it only when you are sure exactly one result exists.

Filter records — get a subset


tenth_students = Student.objects.filter(grade="10th")
Example: all() is like asking the library for every book they have. filter() is like asking for "only science books". get() is like asking for "the book with ISBN number 9781234567890" — there can only be one.

Exclude records


non_tenth = Student.objects.exclude(grade="10th")

Count records


total = Student.objects.count()
print(total)   # Output: 2

Check if records exist


exists = Student.objects.filter(grade="10th").exists()
print(exists)   # Output: True or False

Field Lookups — Filtering with Conditions

Django provides special keywords called field lookups to filter data with conditions. These use double underscores (__):

  • field__exact=value — Exact match (same as field=value).
  • field__iexact=value — Case-insensitive exact match.
  • field__contains=value — Field contains this text.
  • field__icontains=value — Case-insensitive contains.
  • field__startswith=value — Field starts with this text.
  • field__gt=value — Greater than.
  • field__gte=value — Greater than or equal to.
  • field__lt=value — Less than.
  • field__lte=value — Less than or equal to.
  • field__in=[val1, val2] — Field value is one of the listed values.

# Students older than 14
Student.objects.filter(age__gt=14)

# Students whose name contains "Raj" (case-insensitive)
Student.objects.filter(name__icontains="raj")

# Students in grade 9th or 10th
Student.objects.filter(grade__in=["9th", "10th"])
Example: Field lookups are like search filters on a shopping website. You select "Price less than 1000", "Brand contains Nike", and "Rating greater than 4". Django's ORM does the same thing but using Python code instead of checkboxes.

Ordering Results


# Alphabetical order by name
Student.objects.all().order_by('name')

# Reverse alphabetical (descending)
Student.objects.all().order_by('-name')

# Order by age, then by name
Student.objects.all().order_by('age', 'name')

Limiting Results


# Get only the first 5 students
Student.objects.all()[:5]

# Get students from position 5 to 10
Student.objects.all()[5:10]

Updating Records

Update a single record


student = Student.objects.get(id=1)
student.grade = "11th"
student.save()

Update multiple records at once


Student.objects.filter(grade="9th").update(is_active=False)
Example: Updating a single record is like correcting one student's report card manually. Updating multiple records at once is like the teacher stamping "PASSED" on every report card in the class with one motion.

Deleting Records

Delete a single record


student = Student.objects.get(id=1)
student.delete()

Delete multiple records


Student.objects.filter(is_active=False).delete()

Using ORM in Views

Here is how to use the ORM inside a view and pass data to a template:


from django.shortcuts import render
from .models import Student

def student_list(request):
    students = Student.objects.all().order_by('name')
    return render(request, 'student_list.html', {'students': students})

<!-- student_list.html -->
<h1>All Students</h1>
<ul>
{% for student in students %}
    <li>{{ student.name }} — Grade: {{ student.grade }}</li>
{% endfor %}
</ul>

Quick Recap


from school.models import Student

# Create
Student.objects.create(name="Ali", age=15, grade="10th", email="ali@school.com")

# Read
Student.objects.all()
Student.objects.get(id=1)
Student.objects.filter(grade="10th")

# Update
student = Student.objects.get(id=1)
student.grade = "11th"
student.save()

# Delete
student.delete()

Leave a Comment

Your email address will not be published. Required fields are marked *