A Django QuerySet is a collection of database objects returned by the Django ORM. QuerySets allow you to retrieve, filter, sort, update, and delete database records using Python code.
A QuerySet represents a collection of objects retrieved from a database using a Django model.
students = Student.objects.all()
Here, students is a QuerySet containing Student objects.
QuerySets are created through a model's manager, commonly
objects.
Student.objects.all()
The model defines the type of data, while the QuerySet represents matching records.
Django models normally have an objects manager that provides
methods for querying the database.
Student.objects.all()
Student.objects.filter(...)
Student.objects.get(...)
These methods return model objects or QuerySets depending on the operation.
The all() method returns a QuerySet containing all records.
students = Student.objects.all()
You can loop through the returned records:
for student in students:
print(student.name)
The filter() method returns records that match the specified
conditions.
students = Student.objects.filter(
age=20
)
The result is a QuerySet and can contain zero, one, or many records.
Multiple conditions can be passed to filter().
students = Student.objects.filter(
age=20,
is_active=True
)
The conditions are combined using AND behavior.
The exclude() method returns records that do not match the
specified condition.
students = Student.objects.exclude(
age=20
)
This returns students whose age is not 20.
The get() method is used when you expect exactly one matching
object.
student = Student.objects.get(
id=1
)
If no object matches, Django raises DoesNotExist. If multiple
objects match, Django raises MultipleObjectsReturned.
The first() method returns the first object from a QuerySet.
student = Student.objects.order_by(
'name'
).first()
If the QuerySet is empty, first() returns None.
The last() method returns the last object from a QuerySet.
student = Student.objects.order_by(
'name'
).last()
If the QuerySet is empty, last() returns None.
Use order_by() to sort QuerySet results.
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 records represented by
the QuerySet.
total = Student.objects.count()
For a filtered QuerySet:
total = Student.objects.filter(
is_active=True
).count()
The exists() method checks whether a QuerySet contains at least
one result.
if Student.objects.filter(
email="rahul@example.com"
).exists():
print("Student exists")
It is useful when you only need to know whether matching records exist.
The contains lookup can find records where a field contains
specific text.
students = Student.objects.filter(
name__contains="Rah"
)
This can match names containing the specified text.
The icontains lookup performs a case-insensitive containment
search.
students = Student.objects.filter(
name__icontains="rahul"
)
This can match values such as Rahul without requiring the same
letter case.
The startswith lookup finds values beginning with specified text.
students = Student.objects.filter(
name__startswith="A"
)
It can be useful for prefix-based searches.
Django provides several numeric comparison lookups.
Student.objects.filter(age__gt=18)
Student.objects.filter(age__gte=18)
Student.objects.filter(age__lt=30)
Student.objects.filter(age__lte=30)
gt – greater thangte – greater than or equal tolt – less thanlte – less than or equal toQuerySet methods can often be chained together.
students = Student.objects.filter(
age__gte=18
).filter(
is_active=True
).order_by(
'name'
)
The result contains active students aged 18 or older, ordered by name.
QuerySets can be sliced to limit the records returned.
students = Student.objects.all()[:5]
This retrieves the first five records.
students = Student.objects.all()[5:10]
This retrieves a later range of records.
The values() method returns dictionaries instead of complete model
objects.
students = Student.objects.values(
'name',
'age'
)
Each result contains the selected fields as dictionary keys.
The values_list() method returns selected field values as tuples.
students = Student.objects.values_list(
'name',
'age'
)
You can request a single field as a flat list-like result using
flat=True.
names = Student.objects.values_list(
'name',
flat=True
)
The distinct() method can remove duplicate rows from QuerySet
results when duplicates are produced by the query.
cities = Student.objects.values(
'city'
).distinct()
The exact behavior can depend on the query and database backend.
The update() method changes fields on all records matched by a
QuerySet.
Student.objects.filter(
age=20
).update(
age=21
)
This can update multiple records in one database operation.
The delete() method can remove all records represented by a
QuerySet.
Student.objects.filter(
age=18
).delete()
delete(), especially when working with important data.
Django QuerySets are generally lazy. Creating a QuerySet does not necessarily execute the database query immediately.
students = Student.objects.filter(
age__gte=18
)
The query is generally evaluated when Django needs the results, such as when the QuerySet is iterated over.
A QuerySet can be retrieved inside a view and passed 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 a QuerySet passed by the view.
<h2>Students</h2>
<ul>
{% for student in students %}
<li>
{{ student.name }}
- {{ student.age }}
</li>
{% empty %}
<li>No students found.</li>
{% endfor %}
</ul>
QuerySets can be used to create a simple search feature.
keyword = request.GET.get(
'q',
''
)
students = Student.objects.filter(
name__icontains=keyword
)
This retrieves students whose names contain the search keyword without requiring the same letter case.
Get all students:
students = Student.objects.all()
Filter students:
students = Student.objects.filter(
age__gte=18,
is_active=True
)
Order students:
students = Student.objects.filter(
is_active=True
).order_by(
'name'
)
Search students:
students = Student.objects.filter(
name__icontains='rahul'
)
Count students:
total = Student.objects.count()
Check whether students exist:
exists = Student.objects.filter(
is_active=True
).exists()
QuerySets are a core part of the Django ORM. They provide a convenient way to retrieve and manipulate collections of database records.
all() retrieves all records.filter() retrieves matching records.exclude() excludes matching records.get() retrieves one expected object.first() retrieves the first object.last() retrieves the last object.order_by() sorts records.count() counts records.exists() checks whether results exist.values() returns dictionary-style results.values_list() returns selected values.update() changes matching records.delete() removes matching records.objects manager.all() retrieves all records.filter() retrieves records matching conditions.exclude() excludes matching records.get() is used when one specific object is expected.order_by() sorts QuerySet results.count() counts matching records.exists() checks whether matching records exist.Question: Which Django ORM method is used to retrieve records that match specified conditions?