Open In App

Django QuerySet - Order By

Last Updated : 15 Nov, 2025
Comments
Improve
Suggest changes
67 Likes
Like
Report

The order_by() method in Django QuerySets is used to sort results based on one or more fields.

  • Supports sorting in both ascending and descending order.
  • Can sort by fields like name, date, salary, or any model field.
  • Sorting happens at the database level for better performance.
  • Helps display data in a structured and meaningful order.

Understanding the Dataset for order_by()

Consider a project named 'projectApp' with a model 'EmployeeDetails'.

In models.py:

Python
from django.db import models

class EmployeeDetails(models.Model):
    EmployeeId = models.AutoField(primary_key=True)
    EmployeeName = models.CharField(max_length=20)
    EmployeeDepartment = models.CharField(max_length=20, blank=True, null=True)
    Country = models.CharField(max_length=20, blank=True, null=True)
    Salary = models.IntegerField(blank=True)
    
    def __str__(self):
        return self.EmployeeName

After creating this model, run the following two commands to create and apply migrations, which will create the corresponding database tables.

python manage.py makemigrations
python manage.py migrate

Add some sample data via the Django admin or shell before testing.

django31
Snapshot of Database after adding some dummy entries

Using order_by() in the Django Shell

Open the Django shell:

python manage.py shell

1. Sort Employees in Ascending Order by Salary

Python
from yourapp.models import EmployeeDetails

# Retrieve all employees ordered by Salary (lowest first)
employees = EmployeeDetails.objects.all().order_by('Salary')
for emp in employees:
    print(emp.EmployeeName, emp.Salary)

This will display employees starting from the lowest salary:

django32
Snapshot of shell

2. Sort Employees by Salary in Descending Order

Python
# Using '-' prefix to sort descending by Salary
employees = EmployeeDetails.objects.all().order_by('-Salary')
for emp in employees:
    print(emp.EmployeeName, emp.Salary)

The '-' before the field name reverses the order, so the highest salaries appear first:

django33
Snapshot of shell
Python
# Approach 1: Reverse the QuerySet after ascending order
employees = EmployeeDetails.objects.all().order_by('Salary').reverse()

# Approach 2: Using Python list slicing (less efficient)
employees = list(EmployeeDetails.objects.all().order_by('Salary'))[::-1]

for emp in employees:
    print(emp.EmployeeName, emp.Salary)

While these work, using '-Salary' in order_by() is faster and preferred:

django34
Snapshot of shell

4. Sort by Multiple Fields

Python
# Order first by Salary ascending, then by EmployeeName ascending
employees = EmployeeDetails.objects.all().order_by('Salary', 'EmployeeName')
for emp in employees:
    print(emp.EmployeeName, emp.Salary)

Employees are sorted by salary, when salaries are equal, they are sorted alphabetically by name:

django35
Snapshot of shell
Suggested Quiz
3 Questions

What does the order_by() method in Django QuerySets do?

  • A

    Filters records based on conditions

  • B

    Deletes records that do not match order

  • C

    Sorts results based on one or more fields

  • D

    Groups records by a field

Explanation:

order_by() arranges returned objects in a defined order according to specified field(s).

Which syntax will sort a QuerySet by a field named Salary in descending order?

  • A

    .order_by('Salary')

  • B

    .order_by('-Salary')

  • C

    .order_by('Salary', '-')

  • D

    .order_by('-Salary', 'asc')

Explanation:

A minus sign before field name signals descending order, without minus it is ascending.

If a QuerySet does not call order_by() and model metadata does not set default ordering, what can be said about the order of returned records?

  • A

    Records are returned in insertion order always

  • B

    Records are returned in ascending order of primary key

  • C

    Order is unspecified and may vary

  • D

    Records are returned in alphabetical order by default

Explanation:

Without an explicit ordering, the database may return records in any arbitrary order — no guaranteed ordering.

Quiz Completed Successfully
Your Score :   2/3
Accuracy :  0%
Login to View Explanation
1/3 1/3 < Previous Next >

Article Tags :

Explore