Lesson 30 of 60 – Django QuerySets
50%

Django QuerySets

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.

Note: QuerySets are one of the most important parts of the Django ORM. They provide a powerful way to work with database records without writing SQL for common operations.

1. What is a QuerySet?

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.

2. QuerySet and Model

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.

3. The objects Manager

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.

4. all()

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)

5. filter()

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.

6. Multiple Conditions

Multiple conditions can be passed to filter().

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

The conditions are combined using AND behavior.

7. exclude()

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.

8. get()

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.

9. first()

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.

10. last()

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.

11. order_by()

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.

12. count()

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()

13. exists()

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.

14. contains Lookup

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.

15. icontains Lookup

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.

16. startswith Lookup

The startswith lookup finds values beginning with specified text.

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

It can be useful for prefix-based searches.

17. Numeric Lookups

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 than
  • gte – greater than or equal to
  • lt – less than
  • lte – less than or equal to

18. Chaining QuerySet Methods

QuerySet 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.

19. Slicing QuerySets

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.

20. values()

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.

21. values_list()

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
)

22. distinct()

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.

23. update()

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.

24. delete()

The delete() method can remove all records represented by a QuerySet.

Student.objects.filter(
    age=18
).delete()
Warning: Always verify the QuerySet before using delete(), especially when working with important data.

25. QuerySet Lazy Evaluation

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.

26. QuerySet in a View

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}
    )

27. QuerySet in a Template

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>

28. QuerySet with Search

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.

29. Complete QuerySet Example

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()

30. Summary of Django QuerySets

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.
  • QuerySets can be chained together.
  • QuerySets are generally evaluated lazily.

📌 Key Points

  • A QuerySet represents a collection of database objects.
  • QuerySets are commonly created using the model's 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.
  • QuerySet methods can often be chained together.
  • QuerySets are generally lazy and are evaluated when their results are needed.
  • QuerySets can be passed from views to templates.

🧠 Quick Quiz

Question: Which Django ORM method is used to retrieve records that match specified conditions?