Order a Query in descending and ascending in Python Django

In this Python Django tutorial, we will discuss how to arrange or sort the data in Django in ascending and descending order. We will use the order_by query set to arrange the data in increasing and decreasing order and we will also discuss the logic to implement the order_by function.

How to order a Query in descending and ascending order in Python Django.

To order a Query set in descending and ascending order in Python Django, We will use the order_by function. To implement the order_by function we need fields and use this function on the title basis.

We are going to discuss two methods i.e. ascending and descending and we will see how to put ascending records in descending order and descending records in ascending order.

Let’s have a look at the models in a Django app.

class Employee(models.Model):
   name = models.CharField(max_length=120)
   emp_id = models.IntegerField()
   email = models.EmailField()

Order a Django queryset in ascending order

To arrange query set in ascending order in Python Django we will use the order_by functions in the fields in the following manner. We will sort the queryset on “id” which is an autogenerated field in Django.

Employee.objects.filter().order_by('id')
Order a Query in descending and ascending in Python Django
Order a Query in descending and ascending in Python Django

Order a Django queryset in descending order

To arrange the query set in descending order in Python Django we will again use the order_by function but we will use “id” as “-id” in the code to order the query set in descending order.

Employee.objects.filter().order_by('-id')

So these were the methods we used and ordered Django query in ascending and descending order.

Order a Query in descending and ascending in Python Django example
Order a Query in descending and ascending in Python Django example

Conclusion

In this Python Django tutorial, we have learned how to order Django query in ascending and descending order by order_by function using fields in Django and we also used “id” which is an autogenerated field in Django.

READ:  How to encrypt and decrypt password in Django

You may also like to read the following articles: