Lesson 32 of 60 – Reading Records in Django
53%

Reading Records in Django

Reading records means retrieving existing data from the database. Django ORM provides several methods such as all(), get(), filter(), first(), and last() for retrieving model records.

Note: Django ORM allows you to read database records using Python code without writing SQL queries for common operations.

1. What Does Reading Records Mean?

Reading records means retrieving existing rows from a database table. For example, a Student table may contain many student records.

Student.objects.all()

This QuerySet can be used to retrieve the students stored in the database.

2. Reading Records with all()

The all() method returns all records from a model.

students = Student.objects.all()

The result is a QuerySet containing the available Student objects.

3. Looping Through Records

You can use a Python for loop to read each object from a QuerySet.

students = Student.objects.all()

for student in students:
    print(student.name)

Each iteration gives you one Student object.

4. Reading a Specific Record with get()

The get() method is useful when you expect exactly one matching object.

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

print(student.name)

The returned value is a model object rather than a QuerySet.

5. get() and DoesNotExist

If get() cannot find a matching record, Django raises the model's DoesNotExist exception.

student = Student.objects.get(
    id=100
)

If there is no student with ID 100, an exception is raised.

try:

    student = Student.objects.get(id=100)

except Student.DoesNotExist:

    print("Student not found")

6. get() and MultipleObjectsReturned

The get() method expects one object. If multiple records match, Django raises MultipleObjectsReturned.

student = Student.objects.get(
    age=20
)

If several students are aged 20, this query can raise an exception. For multiple results, use filter() instead.

7. Reading Records with filter()

The filter() method returns all records matching the specified conditions.

students = Student.objects.filter(
    age=20
)

The result is a QuerySet and may contain zero, one, or many records.

8. Filtering by Name

You can retrieve records using a specific field value.

students = Student.objects.filter(
    name="Rahul"
)

This returns students whose name matches the specified value.

9. Filtering with Multiple Conditions

Multiple conditions can be provided to filter().

students = Student.objects.filter(
    age=20,
    is_active=True
)

The conditions are combined using AND behavior.

10. Searching with icontains

The icontains lookup can be used for case-insensitive text searches.

students = Student.objects.filter(
    name__icontains="rahul"
)

This can match values such as Rahul, depending on the database backend's case-insensitive behavior.

11. Reading Records with startswith

The startswith lookup finds records whose field starts with specified text.

students = Student.objects.filter(
    name__startswith="A"
)

This can be useful for simple prefix searches.

12. Numeric Filtering

Django provides comparison lookups for numeric fields.

students = Student.objects.filter(
    age__gte=18
)

This retrieves students whose age is greater than or equal to 18.

students = Student.objects.filter(
    age__lt=30
)

This retrieves students whose age is less than 30.

13. Reading the First Record

The first() method returns the first object in a QuerySet.

student = Student.objects.all().first()

if student:
    print(student.name)

If there are no records, first() returns None.

14. Reading the Last Record

The last() method returns the last object from a QuerySet.

student = Student.objects.all().last()

if student:
    print(student.name)

If the QuerySet is empty, last() returns None.

15. Sorting Records with order_by()

The order_by() method sorts records before they are returned.

students = Student.objects.order_by(
    "name"
)

This sorts records by name in ascending order.

students = Student.objects.order_by(
    "-name"
)

The minus sign specifies descending order.

16. Counting Records

The count() method returns the number of matching records.

total_students = Student.objects.count()

print(total_students)

You can also count filtered records.

active_students = Student.objects.filter(
    is_active=True
).count()

17. Checking Whether Records Exist

The exists() method checks whether a QuerySet contains at least one matching record.

if Student.objects.filter(
    email="rahul@example.com"
).exists():

    print("Student found")

This is useful when you only need to know whether a matching record exists.

18. Reading Selected Fields with values()

The values() method can return only selected fields as dictionary-like results.

students = Student.objects.values(
    "name",
    "email"
)

Example result:

{
    "name": "Rahul",
    "email": "rahul@example.com"
}

19. Reading Selected Fields with values_list()

The values_list() method returns selected field values as tuples.

students = Student.objects.values_list(
    "name",
    "age"
)

For a single field, you can use flat=True.

names = Student.objects.values_list(
    "name",
    flat=True
)

20. Limiting Records

QuerySets can be sliced when you only need a limited number of records.

students = Student.objects.all()[:5]

This retrieves the first five records.

students = Student.objects.all()[5:10]

This retrieves records from the specified slice.

21. Reading Records in a View

A common Django pattern is to retrieve records inside a view and send them to a template.

from django.shortcuts import render
from .models import Student

def student_list(request):

    students = Student.objects.all()

    return render(
        request,
        "students/list.html",
        {"students": students}
    )

22. Displaying Records in a Template

A template can loop through the QuerySet and display each record.

<h2>Student List</h2>

<ul>

{% for student in students %}

    <li>
        {{ student.name }}
        - {{ student.email }}
    </li>

{% empty %}

    <li>No students found.</li>

{% endfor %}

</ul>

23. Reading a Record by ID

A common requirement is to display one record using its primary key.

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

The student can then be passed to a template.

return render(
    request,
    "students/detail.html",
    {"student": student}
)

24. Reading a Record Safely with get_object_or_404()

Django provides get_object_or_404() as a convenient way to retrieve an object and return a 404 response if it does not exist.

from django.shortcuts import (
    get_object_or_404
)

student = get_object_or_404(
    Student,
    id=1
)

This is commonly used for detail pages.

25. Searching Records

QuerySets can be used to create search functionality.

keyword = request.GET.get(
    "q",
    ""
)

students = Student.objects.filter(
    name__icontains=keyword
)

The value of q can come from a search form.

26. Combining Search and Ordering

QuerySet methods can be chained together.

students = Student.objects.filter(
    name__icontains=keyword
).order_by(
    "name"
)

This searches for matching names and sorts the results alphabetically.

27. Reading Related Records

Django can also read related objects using relationship fields such as ForeignKey.

class Course(models.Model):

    name = models.CharField(
        max_length=100
    )


class Student(models.Model):

    name = models.CharField(
        max_length=100
    )

    course = models.ForeignKey(
        Course,
        on_delete=models.CASCADE
    )

You can access a student's course using:

student.course.name

28. Complete Student List View

from django.shortcuts import render
from .models import Student

def student_list(request):

    keyword = request.GET.get(
        "q",
        ""
    )

    students = Student.objects.all()

    if keyword:

        students = students.filter(
            name__icontains=keyword
        )

    students = students.order_by(
        "name"
    )

    return render(
        request,
        "students/list.html",
        {
            "students": students,
            "keyword": keyword
        }
    )

This example retrieves students, optionally searches by name, orders the results, and sends them to a template.

29. Common Mistakes While Reading Records

  • Using get() when multiple records may match.
  • Not handling DoesNotExist when using get().
  • Forgetting to import the model.
  • Using incorrect field names in filters.
  • Forgetting to pass the QuerySet to the template.
  • Using filter() when a single object is actually required.
  • Not checking whether a QuerySet is empty.
  • Forgetting to use icontains for a case-insensitive search when appropriate.
  • Not ordering results when a specific display order is required.

30. Summary of Reading Records

Django ORM provides many methods for reading existing database records.

  • all() retrieves all records.
  • get() retrieves one expected object.
  • filter() retrieves matching records.
  • first() retrieves the first object.
  • last() retrieves the last object.
  • order_by() sorts records.
  • count() counts records.
  • exists() checks whether matching records exist.
  • values() retrieves selected fields as dictionaries.
  • values_list() retrieves selected values.
  • get_object_or_404() is useful for detail pages.
  • QuerySets can be filtered, sorted, sliced, and passed to templates.

📌 Key Points

  • Reading records means retrieving existing database data.
  • all() retrieves all objects.
  • filter() retrieves objects matching conditions.
  • get() is used when one object is expected.
  • first() and last() retrieve individual objects from a QuerySet.
  • order_by() sorts QuerySet results.
  • count() returns the number of matching records.
  • exists() checks whether matching records exist.
  • values() and values_list() can retrieve selected fields.
  • get_object_or_404() is useful when a missing object should result in a 404 response.
  • QuerySets can be passed from views to templates.

🧠 Quick Quiz

Question: Which Django ORM method is commonly used to retrieve multiple records that match a condition?