Django Query Set - Order By
Last Updated : 22 May, 2025
order_by() method in Django QuerySets is used to sort query results based on one or more fields, either in ascending or descending order. This helps display data sorted by criteria like salary, name, date, etc., directly from the database query.
In this article we will learn all about order_by method of QuesrySets by performing multiple operations over a dataset, for this we need to first create a model
Creating Model: EmployeeDetails
Assuming you have the following model defined 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
Make sure you have migrated this model:
python manage.py makemigrations
python manage.py migrate
Add some sample data via the Django admin or shell before testing.
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:
Snapshot of shell2. 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:
Snapshot of shell3. Alternative Descending Order Approaches (Not Recommended)
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:
Snapshot of shell4. 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:
Snapshot of shellUnfortunately, in the above example, our database have no entries with same salaries and thats why the output looks like a regular salary based sorted list
Similar Reads
Django Query Set - get A QuerySet is a collection of data retrieved from the database. You can think of it as a list of objects. QuerySets make it easier to get only the data you need by letting you filter, sort, and organize your data early on before actually fetching it from the database.In this article, we will learn h
3 min read
Perform OR Condition in Django Queryset While querying a database using Django's ORMâObject-Relational Mappingâone of the most common requirements would probably be filtering data on more than one condition. By default, Django supports filtering data with AND conditions. However, specific techniques have to be used when you need to filter
3 min read
How to Query as GROUP BY in Django? In Django, the powerful ORM (Object-Relational Mapping) allows developers to interact with databases using Python code. One common database operation is the GROUP BY query, which groups rows sharing a property so that aggregate functions can be applied to each group. This article will guide you thro
3 min read
Python Django Queryset Filtering In Django, QuerySet filtering allows you to retrieve only the data you need from the database. QuerySets help you filter, sort and organize your data efficiently, making it easy to interact with your models.This article will explore how to filter datasets using Djangoâs filter(), exclude() and advan
2 min read
How to combine multiple QuerySets in Django? QuerySets allow you to filter, order, and manipulate data from your database using a high-level Pythonic syntax. However, there are situations where you may need to combine multiple QuerySets into a single QuerySet to work with the data more efficiently. This article will explore various methods to
5 min read