![]() |
VOOZH | about |
order_by() method in Django QuerySets is used to sort results based on one or more fields.
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.
Open the Django shell:
python manage.py shell
This will display employees starting from the lowest salary:
The '-' before the field name reverses the order, so the highest salaries appear first:
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.
Employees are sorted by salary, when salaries are equal, they are sorted alphabetically by name: