Skip to content
thesarfo

Note

Sorting Data

Sorting a queryset with order_by(), reversing direction, sorting by multiple fields, and the earliest()/latest() shortcuts.

views 0

There is a method called order_by() that helps you sort the result by one or more fields.

For instance

queryset = Product.objects.order_by('title')

The above code sorts all the products by their title in alphabetical(ascending) order.

To change the sort direction, ie descending order, simply add a negative(-) sign to the field.

queryset = Product.objects.order_by('-title')
# sorts all products by title in reverse order

You can also sort by multiple fields. For instance

queryset = Product.objects.order_by('unit_price', '-title')

The above code sorts all the products by unit price in ascending order, and title in descending order.

Since the order_by method returns a queryset object, you can even apply the reverse() method to further query your data.

For instance, i want to sort the products from cheapest to expensive and in ascending order by title.

queryset = Product.objects.order_by('unit_price', 'title').reverse()

Useful Methods

queryset = Product.objects.order_by('unit_price')[0]
queryset = Product.objects.earliest('unit_price')
# both of the above methods sorts the products by unit price, and then returns the first object.
# but the earliest method is much simpler, as it does not return a queryset
queryset = Product.objects.latest('unit_price') #does the reverse of the earliest method