Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Django
  • Views
  • Model
  • Template
  • Forms
  • Jinja
  • Python SQLite
  • Flask
  • Json
  • Postman
  • Interview Ques
  • MongoDB
  • Python MongoDB
  • Python Database
  • ReactJS
  • Vue.js
Open In App
Next Article:
Django Query Set - Order By
Next article icon

Django Query Set - Order By

Last Updated : 22 May, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

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.

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

3. 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:

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

Unfortunately, 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


Next Article
Django Query Set - Order By

A

ap1079997
Improve
Article Tags :
  • Python
  • Python Django
Practice Tags :
  • python

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
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences