QuerySet represents a cluster of data in the database. It helps us to slice out the data that we actually need. It is an efficient way to access the data, as it does not perform any database activity until we do something to evaluate the QuerySet. In this tutorial we use order_by
() in Django.
What is Order By?
Order By is a keyword to sort the data either in ascending or descending order. Here in this tutorial, we are using Django Query Set to perform the Order By operation. Let’s create a simple project in Django to store the Employee details.
Prerequisite: We have to make sure a few things are available in our system.
- Any Python IDE. In this tutorial, we are using vs code.
- Django Installed in the system.
The basic setup of the Django project
Step 1: Create a Virtual Environment.
Step 2: Now to start a Django project in your system, write the following command in the command prompt or terminal.
django-admin startproject projectName
Step 3: A new folder is created in your system. In Django, it is known as an app. It must contain a manage.py file.
cd projectName
Step 4: Now run your project by using the command below.
python manage.py runserver
Step 5: Open settings.py and wire up your app under INSTALLED_APPS. In our case, we need to add OrderByPractice.
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'OrderByPractice'
]
Step 6: Create a template folder and add a ShowEmployeeDetails.html file. You also need to specify ‘templates‘ under the ‘DIRS’ attribute in settings.py
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': ['templates'],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
Step 7: The Django web framework includes a default object-relational mapper (ORM). It is used to interconnect with the Database. Django by default uses SQLite as a database. Create models.py and define EmployeeDetails class. This EmployeeDetails class represents a table and fields (Ex. EmployeeName, EmployeeDepartment) represent columns in a table.
Python3
from django.db import models class EmployeeDetails(models.Model): EmployeeId = models.AutoField(primary_key = True ) EmployeeName = models.CharField(max_length = 20 ) EmployeeDepartment = models.CharField(max_length = 20 , blank = True , null = True ) Country = models.CharField(max_length = 20 , blank = True , null = True ) Salary = models.IntegerField(blank = True ) |
Step 8: Create your Action method in views.py. It is used to fetch all the data present in the table and renders it in html file.
Python3
from django.shortcuts import render, HttpResponse from . models import EmployeeDetails def ShowDetails(request): users = EmployeeDetails.objects. all ().values() return render(request, 'ShowEmployeeDetails.html' , context = { 'users' : users}) |
Step 9: You also need to set the path in the URL pattern. Navigate to urls.py.
Python3
from django.contrib import admin from django.urls import path, include from . import views urlpatterns = [ path( 'admin/' , admin.site.urls), path(' ', views.ShowDetails, name=' ShowDetails') ] |
Step 10: Register your model in admin.py. So that your table is visible in build in Django Admin Panel. We talk about this in the later part of the tutorial.
Python3
from django.contrib import admin from . models import EmployeeDetails # Register your models here. admin.site.register(EmployeeDetails) |
Step 11: Now run the migrations.
python manage.py migrate
python manage.py makemigrations
After running the above commands, you can able to see a migration script present in the migrations folder.
Sometimes you get a “no such table” exception. This issue is resolved by the below command. It basically sync-up your migration script with the database.
python manage.py migrate --run-syncdb
Step 12: Add some code in ShowEmployeeDetails.html file. Here we are displaying EmployeeName, EmployeeDepartment, Country, and Salary.
HTML
<!DOCTYPE html> < html lang = "en" > < head > < meta charset = "UTF-8" > < meta http-equiv = "X-UA-Compatible" content = "IE=edge" > < meta name = "viewport" content = "width=device-width, initial-scale=1.0" > < title >Document</ title > </ head > < body > < h1 >Employee Details</ h1 > < form action = "{% url 'ShowDetails' %}" > {% csrf_token %} < table style = "border:orange; border-width:5px; border-style:solid;" > < tr > < th >EmployeeName</ th > < th >EmployeeDepartment</ th > < th >Country</ th > < th >Salary</ th > </ tr > {% for user in users %} < tr > < td >{{user.EmployeeName}}</ td > < td >{{user.EmployeeDepartment}}</ td > < td >{{user.Country}}</ td > < td >{{user.Salary}}</ td > </ tr > {% endfor %} </ table > </ form > </ body > </ html > |
Step 13: Create a super user.
python manage.py createsuperuser
After that, you need to enter Username and Password
Now run your project and write /admin after hostname and press enter
Step 14: Now add employee details.
Fill in all fields and hit the Save button. If you want to add more employees then you can also use Save and add another.
Step 15: Perform Query Set – Order By
- Sort the Employees in Ascending order
- Sort the Employees in Descending order
Sort the Employees in Ascending order
If there is a requirement that we need to sort the Employees in ascending order by salary then we can use order_by in Django.
There is one line of code that you need to change in the ShowDetails Action method under view.py.
users = EmployeeDetails.objects.all().order_by('Salary').values()
when you run your project. Then you can see the Employee Details in UI. You can observe in the image below that Tony Stark has the lowest salary and appear at the top.
Sort the Employees in Descending order
If you want the sort the Employees in Descending order by Salary. Then we have three approaches
users = EmployeeDetails.objects.all().order_by('Salary').values()[::-1]
or
users = EmployeeDetails.objects.all().order_by('Salary').values().reverse()
or
users = EmployeeDetails.objects.all().order_by('-Salary').values()
You can observe in the image below that Bhuwan has the highest salary appear at the top.
Perform Query Set – Multiple Order By
Multiple order means first by one and then by other, for multiple Order By you just need to add a second argument in the order_by() method. Now we need to order the data on the basis of Salary and then by Employee Name.
users = EmployeeDetails.objects.all().order_by('Salary','EmployeeName').values()
You can observe in the image below that all these three Employees Amit Patil, Annie Frank, and Tony Stark
has the same Salary but we get the EmployeeName in alphabetical order.
That’s it for this article. Happy Coding!