How to Sort Django QuerySet in Ascending and Descending Order?
In previous tutorial, we have learnt how to create model and form in Django. This tutorial is about reading model data and sorting it.
Let’s say you have this contact model in your Django App.
class ContactModel(models.Model): name = models.CharField(max_length=120) mobile = models.IntegerField() email = models.EmailField()
When we read the data from the model, Django returns queryset. Django has
order_by method to sort the queryset in ascending and descending order. You can order the queryset on any field.
In the Django model, there is one autogenerated ‘id’ field. You can use any of the fields (id name, mobile or name) to sort the queryset.
Sort by Ascending Order
Let’s sort the queryset on ‘id’ in ascending order.
Sort by Descending Order (desc)
Use the not sign ‘-‘ to sort the queryset in reverse order aka descending order (desc).
Note: Here we are reading all the entries from the model. You can also use
filter() method instead of
all() method to filter out some entries.
Django Order by Multiple Fields
You can also use the multiple fields to sort the queryset by passing multiple fields as parameters to
How does it work?
First, it sorts the queryset by name (first field). If the person has the same name, it sorts queryset by mobile number (second field). If all the entries in the queryset have a unique name, the second field ‘mobile’ does not make any difference.
order_by method works with any type of model fields like text string, date, time, number, etc.
Usually, models are read and ordered in the Django view function before passing it to the HTML template.
Hope you find this quick tutorial on how sort Django queryset in ascending and descending order helpful. Any doubt? Let me know in the comment.