Master Django ORM: 10 Powerful QuerySet Methods You Need to Know

This tutorial walks through ten advanced Django ORM QuerySet methods—exclude, values, values_list, select_related, order_by, exists, count, first/last, in_bulk, and explain—showing how each works with practical code examples using Student and School models.

MaGe Linux Operations
MaGe Linux Operations
MaGe Linux Operations
Master Django ORM: 10 Powerful QuerySet Methods You Need to Know

We all know Django provides a powerful out‑of‑the‑box ORM, and with ORMk we can modify the database without writing SQL, using methods such as filter(), get(), all(), update() and delete(). In daily work most people only use those.

Beyond those basics, Django ORM offers many other powerful methods. This article introduces their practical usage.

exclude()

values()

values_list()

select_related()

order_by()

exists()

count()

first() and last()

in_bulk()

explain()

We will use the following Student model as an example (defined in models.py).

class Student(models.Model):
    name = models.CharField(max_length=100)
    grade = models.IntegerField()
    section = models.CharField(max_length=10)
    school = models.ForeignKey(School, on_delete=models.CASCADE)
    blood_group = models.CharField(max_length=10)
    mobile = models.CharField(max_length=20)
    address = models.TextField()
    def __str__(self):
        return self.name

The student table has a foreign‑key relationship with the school table.

class School(models.Model):
    name = models.CharField(max_length=100)
    email = models.EmailField(null=True, blank=True)
    address = models.TextField()
    def __str__(self):
        return self.name

1. exclude()

The exclude() method returns a QuerySet that omits the records matching the given condition.

>> queryset = Student.objects.all()
>>> queryset
<QuerySet [<Student: Regina Johnson>, <Student: Eva Smith>, <Student: Jessie Smith>, <Student: John David>]>
>>> queryset = Student.objects.exclude(name='Eva Smith')
>>> queryset
<QuerySet [<Student: Regina Johnson>, <Student: Jessie Smith>, <Student: John David>]>

2. values() values() returns a QuerySet of dictionaries instead of model instances.

>> Student.objects.values()
<QuerySet [{ 'id': 1, 'name': 'Regina Johnson', 'grade': 10, 'section': 'A', 'school_id': 1, 'blood_group': 'A+', 'mobile': '9791684645', 'address': '93 Jessica Ln, Depew, NY, 14043'}, ...]>

Providing field names as arguments returns only those fields.

>> Student.objects.values('id', 'name')
<QuerySet [{ 'id': 1, 'name': 'Regina Johnson'}, { 'id': 3, 'name': 'Eva Smith'}, { 'id': 4, 'name': 'Jessie Smith'}, { 'id': 5, 'name': 'John David'}]>

3. values_list() values_list() works like values() but returns tuples.

>> Student.objects.values_list('id', 'name')
<QuerySet [(1, 'Regina Johnson'), (3, 'Eva Smith'), (4, 'Jessie Smith'), (5, 'John David')]>

Using flat=True with a single field returns a flat list.

>> Student.objects.values_list('name', flat=True)
<QuerySet ['Regina Johnson', 'Eva Smith', 'Jessie Smith', 'John David']>

Note: flat=True is invalid when more than one field is supplied.

>> Student.objects.values_list('id', 'name', flat=True)
TypeError: 'flat' is not valid when values_list is called with more than one field.

4. select_related()

This method reduces database hits by performing a SQL join and retrieving related objects in a single query.

>> student = Student.objects.get(pk=1)
>>> student.school
<School: Montfort>
>>> student = Student.objects.select_related('school').get(pk=1)
>>> student.school  # school is already retrieved, no extra query
<School: Montfort>

5. order_by() order_by() changes the default ordering of a QuerySet. Example ordering by name ascending and descending:

>> Student.objects.order_by('name')
<QuerySet [<Student: Eva Smith>, <Student: Jessie Smith>, <Student: John David>, <Student: Regina Johnson>]>
>>> Student.objects.order_by('-name')
<QuerySet [<Student: Regina Johnson>, <Student: John David>, <Student: Jessie Smith>, <Student: Eva Smith>]>

6. exists()

Returns True if the QuerySet contains any records, otherwise False.

>> Student.objects.filter(name='Regina Johnson').exists()
True
>>> Student.objects.filter(name='Regina David').exists()
False

7. count()

Counts the number of records in a QuerySet.

>> Student.objects.count()
4
>>> Student.objects.filter(name='Regina Johnson').count()
1

8. first() and last() first() returns the first object; last() returns the last object of a QuerySet.

>> Student.objects.all().first()
<Student: Regina Johnson>
>>> Student.objects.all().last()
<Student: John David>

Indexing like queryset[0] works, but negative indexing is not supported; last() should be used instead.

>> Student.objects.all()[0]
<Student: Regina Johnson>
>>> Student.objects.all()[-1]
AssertionError: Negative indexing is not supported.

9. in_bulk()

Accepts a list of IDs and returns a dictionary mapping each ID to its model instance. If no IDs are provided, all objects are returned.

>> students = Student.objects.in_bulk([1, 4])
>>> students[1].name
'Regina Johnson'
>>> students[4].name
'Jessie Smith'

10. explain()

Returns the query execution plan as a string, useful for performance analysis.

>> Student.objects.filter(pk=1).explain()
'2 0 0 SEARCH TABLE student_student USING INTEGER PRIMARY KEY (rowid=?)'

Hope this article helps you master these Django ORM methods.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

databaseDjangoORMQuerySet
MaGe Linux Operations
Written by

MaGe Linux Operations

Founded in 2009, MaGe Education is a top Chinese high‑end IT training brand. Its graduates earn 12K+ RMB salaries, and the school has trained tens of thousands of students. It offers high‑pay courses in Linux cloud operations, Python full‑stack, automation, data analysis, AI, and Go high‑concurrency architecture. Thanks to quality courses and a solid reputation, it has talent partnerships with numerous internet firms.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.