0% found this document useful (0 votes)
3 views

Django ORM Basics

The document explains Object-Relational Mapping (ORM) in Django, which allows developers to interact with databases using Python classes instead of raw SQL. It details how to create models, perform CRUD operations, and utilize QuerySets to manage data effectively. The advantages of using Django's ORM include faster development, easier maintenance, and a focus on programming logic over complex SQL queries.

Uploaded by

Sumit Sinha
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Django ORM Basics

The document explains Object-Relational Mapping (ORM) in Django, which allows developers to interact with databases using Python classes instead of raw SQL. It details how to create models, perform CRUD operations, and utilize QuerySets to manage data effectively. The advantages of using Django's ORM include faster development, easier maintenance, and a focus on programming logic over complex SQL queries.

Uploaded by

Sumit Sinha
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 6

Django ORM Basics

Object Relationship Mapping - ORM


What is ORM
Usually, the type of system used in an Object-Oriented language such as Python contains types that
are non-scalar and every time, they cannot be represented only in primitive types such as integers
and strings.

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 model is a Python class that subclasses django.db.models.Model

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.

Next, open the Interactive shell.

It is important to know that these commands are the same if you are on Windows or Mac.

(djenv) C:\djenv\demoproject>python manage.py shell


Create an object of the Customer class. Give a string parameter to the constructor. The save()
method of the models.Model class creates a row in the Customer table.
>>> from demoapp.models import Customer
>>> c=Customer(name="Henry")
>>> c.save()
Adding a model object
The Customer.objects gives the Manager of the model. It handles all the CRUD operations on the
database table. For example, an object can also be created with the create() method as follows:
>>> Customer.objects.create(name="Hameed")
<Customer: Customer object (2)>
The create() method actually performs the INSERT operation of SQL.

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

Object-Relational Mapping (ORM) Explained Simply

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.

Example: Creating Models

python

from django.db import models

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:

The `Customer` model represents customers.


The `Vehicle` model represents vehicles and has a foreign key linking to `Customer` (one customer
can have multiple vehicles).

Querying the Database Using ORM

1. Creating & Saving Data

Open Django’s shell:

sh

python manage.py shell

Now, create a new customer and save it:

python

from demoapp.models import Customer

c = Customer(name="Henry")
c.save()

OR, use `create()` to save directly:

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 4/6
python

Customer.objects.create(name="Hameed")

2. Adding Related Data

To add vehicles for a specific customer:

python

from demoapp.models import Vehicle

c = Customer.objects.get(name="Hameed")

Vehicle.objects.create(name="Honda", customer=c)
Vehicle.objects.create(name="Toyota", customer=c)

3. Fetching Data

Retrieve all customers:

python

customers = Customer.objects.all()
print([c.name for c in customers]) # Output: ['Henry', 'Hameed']

Fetch all vehicles and their associated customer names:

python

vehicles = Vehicle.objects.all()
for v in vehicles:
print(v.name, ":", v.customer.name)

Output:

yaml

Honda : Hameed
Toyota : Hameed

4. Filtering Data

Get customers whose names start with "H":

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 5/6
python

Customer.objects.filter(name__startswith="H")

5. Updating Data

Change "Henry" to "Helen":

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()

Why Use ORM?

✅ 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

You might also like