This post will guide you through the basics of Django ORM. First, we set up a typical Django app, then create simple models for an HR application and demonstrate the essential Django ORM commands. For this tutorial you need to have Python 3 installed along with venv package. Command line instructions given here will work on any Linux, macOS or WSL in Windows. So, let’s begin…
First create a new folder:
mkdir myapp
Go inside this newly created folder:
cd myapp
(Note: From now on wards all the commands entered in this tutorial are from root position of this myapp folder.)
Create virtual environment:
python3 -m venv .env
Mount virtual environment:
source .env/bin/activate
Install Django
pip install django
The above command will install Django. Now create a project by entering following command (don’t forget the full-stop at the end):
django-admin startproject project .
Then create an app named hrm:
python manage.py startapp hrm
Amend project/settings.py as follows in order to add hrm app into the project:
INSTALLED_APPS = [
"hrm",
# ...
]
Now, open hrm/models.py and create a couple of models by inserting following code:
from django.db import models
class Department(models.Model):
name = models.CharField(max_length=100, unique=True)
def __str__(self):
return f"{self.name}"
class Employee(models.Model):
name = models.CharField(max_length=70)
department = models.ForeignKey(Department, on_delete=models.CASCADE)
salary = models.IntegerField()
def __str__(self):
return f"{self.name}"
Make migrations by entering following command:
python manage.py makemigrations
Then migrate the migrations:
python manage.py migrate
Now open Django interactive shell by executing:
python manage.py shell
And then execute following in shell to import hrm‘s models:
from hrm.models import *
Create records
Let’s create some data. First create a couple of departments:
d1=Department.objects.create(name="Marketing")
d2=Department.objects.create(name="IT")
And then create some employees:
Employee.objects.create(name="Maria Lopez", department=d1, salary=75000)
Employee.objects.create(name="John Smith", department=d1, salary=52000)
Employee.objects.create(name="Jane Rose", department=d2, salary=91000)
Employee.objects.create(name="Mike Ted", department=d2, salary=45000)
(Hint: if things get messy while entering data, you may exit the shell by exit() command and then empty the database by executing python manage.py flush)
Retrieve data
Enter following to list all employees:
Employee.objects.all()
Enter following to get record having id=1
Employee.objects.get(id=1)
Enter following to list names with salaries of all employees:
employees=Employee.objects.all()
for e in employees:
print(e.name, ' ', e.salary)
(Hint: As you are in shell mode and the above code contains block of Python statements, so Enter will need to be pressed a couple of times.)
Updating Data
You can easily update records you’ve already saved.
First, let’s retrieve the record we want to update – we’ll use the record for “John Smith”. Then we’ll update the record with new salary:
# Retrieve the employee object
e = Employee.objects.get(id=2)
# Change a field's value
e.salary = 60000
# Save the changes to the database
e.save()
# Verify the update
Employee.objects.get(id=2).salary
Deleting Data
To remove a record from the database, you call the .delete() method on the model instance.
# Retrieve the employee object
e = Employee.objects.get(id=1)
# Delete the employee record
e.delete()
# Retrieve all and see the first record is gone
Employee.objects.all()
Filtering records
The .filter() method is one of the most powerful tools in the Django’s ORM. Let’s find the employees whose names contain alphabets ‘ohn’:
Employee.objects.filter(name__contains="ohn")
You can also chain more than one filters. Now, let’s find employees who are in the ‘IT’ department AND have a salary greater than or equal to 50,000:
Employee.objects.filter(department__name="IT").filter(salary__gte=50000)
Using OR Logic with Q-objects
To use OR logic (find employees in ‘IT’ OR with a salary of 60,000), you need to use Q-objects:
from django.db.models import Q
# Find employees in IT OR with a salary of 60000
Employee.objects.filter(Q(department__name="IT") | Q(salary=60000))
Following Relationships (The ‘Double-Underscore’ Syntax)
You must have noticed the double-underscore (__) syntax in above queries; one of the highlights of the Django ORM is how easy it is to traverse relationships using the double-underscore syntax.
Filtering by Foreign Key Attributes
As you can see in the .filter() query above that the Employee objects were filtered based on a field (‘name’) in the related Department model.
Employee.objects.filter(department__name='IT')
Reverse Relationship
You can also start from the parent model (Department) and get all related children (Employee objects). By default, Django creates a reverse relationship name using modelname_set.
# Get the 'IT' department object
dept = Department.objects.get(name='IT')
# List all employees in that department
dept.employee_set.all()
That’s it for now. Remember, ORM is a very powerful tool which makes communication with the databases quite easy.
Enter exit() to quit Django shell.