In Django, the orderby method is not a built-in method for models. However, you can achieve ordering of querysets by using the order_by() method. The order_by() method allows you to specify how you want the query results to be sorted.
Say you want to sort the Persons
with their first name and retrieve the result, you can do that in the following way :
Person.objects.all().order_by('first_name')
As you can see the result is sorted in ascending
order based on the first_name
field.
Similarly to sort in descending
order, you need to add a (-
) sign before the field name as follows :
Person.objects.all().order_by('-first_name')
Because of the -
sign it will return in descending
order.
You can order by one or more fields, and you can mix ascending and descending order as needed. Multiple fields are separated by commas:
Person.objects.all().order_by('first_name','-last_name')
In this example, the records are first sorted in ascending order by the first_name
field, and if the first_name
field are same, they are then sorted in descending
order by the last_name
field.
You can also use the order_by()
method in combination with other query methods and filters to create complex queries with specific sorting requirements.
Remember that the order_by()
method returns a new queryset with the specified ordering, it doesn't modify the original queryset in place. If you want to chain multiple ordering conditions, you can call order_by()
multiple times on the same queryset.