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 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.
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.
You may also like to read the following articles:
- Error: Django Python setup.py egg_info failed
- Django IntegrityError at /modelname/
- How to create an API in Python Django
I am Bijay Kumar, a Microsoft MVP in SharePoint. Apart from SharePoint, I started working on Python, Machine learning, and artificial intelligence for the last 5 years. During this time I got expertise in various Python libraries also like Tkinter, Pandas, NumPy, Turtle, Django, Matplotlib, Tensorflow, Scipy, Scikit-Learn, etc… for various clients in the United States, Canada, the United Kingdom, Australia, New Zealand, etc. Check out my profile.