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.
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.
The all() method returns all records from a model.
students = Student.objects.all()
The result is a QuerySet containing the available Student objects.
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.
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.
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")
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.
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.
You can retrieve records using a specific field value.
students = Student.objects.filter(
name="Rahul"
)
This returns students whose name matches the specified value.
Multiple conditions can be provided to filter().
students = Student.objects.filter(
age=20,
is_active=True
)
The conditions are combined using AND behavior.
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.
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.
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.
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.
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.
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.
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()
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.
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"
}
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
)
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.
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}
)
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>
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}
)
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.
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.
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.
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
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.
get() when multiple records may match.DoesNotExist when using get().filter() when a single object is actually required.icontains for a case-insensitive search when appropriate.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.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.Question: Which Django ORM method is commonly used to retrieve multiple records that match a condition?