Django ORM Basics
Django ORM Basics
On the other hand, data types in tables of a relational database are of primary types, that is integer
and string.
Therefore, the program needs to convert objects in scalar data to interact with a backend database.
Object-oriented programming languages use Object Relation Mapping (ORM) to interact with
Structured Query Language (SQL), both of which are incompatible.
The ORM layer maps a class to a table in a relational database, with its attributes matching the
table's field structure.
The ORM library lets you perform the database operations in an object-oriented way instead of
executing raw SQL queries.
This allows you to focus more on the programming logic than the backend database operations.
Object Relational Mapping or ORM is the ability to create a SQL query using object-oriented
programming language such as Python. This enables a quick turnaround time in fast production
environments that need constant updates.
Each attribute of the model represents a database field. Essentially you can think of a model as a
Python object, and models help developers create, read, update and delete objects, commonly
called the CRUD operations.
Django has its own ORM layer. Its migration mechanism propagates the models in database tables.
You need to construct a QuerySet via a Manager of your model class to retrieve objects from your
database.
QuerySet
Let's try to understand how QuerySet is constructed and handled with an example. To begin with,
add the following models in the Django app named demoapp.
from django.db import models
class Customer(models.Model):
name = models.CharField(max_length=255)
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 1/6
class Vehicle(models.Model):
name = models.CharField(max_length=255)
customer = models.ForeignKey(
Customer,
on_delete=models.CASCADE,
related_name='Vehicle'
)
The idea is to create two tables, Customer and Vehicle, with a one-to-many relationship. Apply the
migrations and you will see these two tables in the project's database.
It is important to know that these commands are the same if you are on Windows or Mac.
Now, let us add two objects to the Vehicle model. Note that one of the fields in the Vehicle model
refers to an object of the Customer table as ForeignKey. Fetch the Customer object with a primary
key = 2.
>>> from demoapp.models import Customer, Vehicle
>>> c=Customer.objects.get(pk=2)
>>> c.name
'Hameed'
This object is used as the value of the customer attribute in the Vehicle object.
>>> v=Vehicle(name="Honda", customer=c)
>>> v.save()
>>> v=Vehicle(name="Toyota", customer=c)
>>> v.save()
Similarly, add two vehicles for Customer "Henry".
>>> c=Customer.objects.get(name="Henry")
>>> Vehicle.objects.create(name="Ford", customer=c)
<Vehicle: Vehicle object (3)>
>>> Vehicle.objects.create(name="Nissan", customer=c)
<Vehicle: Vehicle object (4)>
Fetch model objects
A QuerySet represents a collection of objects from your database. It represents a SELECT query. To
fetch all the objects, use the all() method of the Manager.
model.objects.all()
The all() method returns a list of objects. You can iterate over it with the usual for loop or list
comprehension technique.
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 2/6
>> lst=Customer.objects.all()
>>> [c.name for c in lst]
['Henry', 'Hameed']
You can apply filters to the data fetched from the model. This is used to fetch objects satisfying the
given criteria. In SQL terms, a QuerySet equates to a SELECT statement, it is like applying a WHERE
clause.
model.objects.filter(criteria)
For example, use the following statement to retrieve all the customers with names starting with 'H'.
mydata = Customer.objects.filter(name__startswith='H')
Similarly, you can retrieve the objects of the Vehicle model. Remember that the Vehicle object refers
to a customer object. You can retrieve the attributes of the related customer as follows:
>>> lst=Vehicle.objects.all()
>>> for v in lst:
... print (v.name, " : ", v.customer.name)
...
Honda : Hameed
Toyota : Hameed
Ford : Henry
Nissan : Henry
Updating and removing a model object
To update an object, such as changing the Customer's name from Henry to Helen, assign a new
value to the name attribute and save.
>>> c=Customer.objects.get(name="Henry")
>>> c.name="Helen"
>>> c.save()
Similarly, the delete() method of the model manager physically removes the corresponding row in
the model's mapped table.
>>> c=Customer.objects.get(pk=4)
>>> c.delete()
(1, {'demoapp.Customer': 1})
-> make it easy to understand
What is ORM?
In object-oriented programming (OOP), applications use objects, but relational databases store data in
tables (rows and columns). ORM (Object-Relational Mapping) acts as a bridge, converting objects into
database-friendly formats and vice versa.
Instead of writing SQL queries manually, ORM allows developers to interact with databases using an
object-oriented approach.
ORM in Django
Django provides its own ORM system, making it easy to work with databases using Python code instead
of raw SQL.
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 3/6
A model is a Python class representing a database table.
Each attribute in the model corresponds to a column in the table.
Django’s ORM handles CRUD (Create, Read, Update, Delete) operations seamlessly.
python
class Customer(models.Model):
name = models.CharField(max_length=255)
class Vehicle(models.Model):
name = models.CharField(max_length=255)
customer = models.ForeignKey(
Customer,
on_delete=models.CASCADE,
related_name='vehicles'
)
Here:
sh
python
c = Customer(name="Henry")
c.save()
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 4/6
python
Customer.objects.create(name="Hameed")
python
c = Customer.objects.get(name="Hameed")
Vehicle.objects.create(name="Honda", customer=c)
Vehicle.objects.create(name="Toyota", customer=c)
3. Fetching Data
python
customers = Customer.objects.all()
print([c.name for c in customers]) # Output: ['Henry', 'Hameed']
python
vehicles = Vehicle.objects.all()
for v in vehicles:
print(v.name, ":", v.customer.name)
Output:
yaml
Honda : Hameed
Toyota : Hameed
4. Filtering Data
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 5/6
python
Customer.objects.filter(name__startswith="H")
5. Updating Data
python
c = Customer.objects.get(name="Henry")
c.name = "Helen"
c.save()
6. Deleting Data
Remove a customer:
python
c = Customer.objects.get(pk=4)
c.delete()
✅ No need to write raw SQL – Use Python to interact with the database.
✅ Faster development – Focus on business logic instead of database queries.
✅ Easier maintenance – ORM abstracts away complex SQL queries.
Django’s ORM makes database interactions simpler, faster, and more efficient. 🚀
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 6/6