VOOZH about

URL: https://www.geeksforgeeks.org/python/django-query-set-order-by/

⇱ Django QuerySet - Order By - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Django QuerySet - Order By

Last Updated : 11 May, 2026

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

Consider a project named 'projectApp' with a model 'EmployeeDetails'. In models.py:

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

Open the Django shell:

python manage.py shell

1. Sort Employees in Ascending Order by Salary

This will display employees starting from the lowest salary:

👁 django32
Snapshot of shell

2. Sort Employees by Salary in Descending Order

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

👁 django33
Snapshot of shell

3. Alternative Descending Order Approaches

While these approaches work, using -Salary with order_by() is often the most direct option. reverse() can also be useful when reversing an existing ordering.

👁 django34
Snapshot of shell

4. Sort by Multiple Fields

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

👁 django35
Snapshot of shell
Comment
Article Tags:
Article Tags: