Day 11 – ORM with Django: Simplifying Database Operations

Description

Writing raw SQL queries can be powerful but also repetitive and error-prone. Django introduces an ORM (Object Relational Mapper) that allows you to interact with your database using Python classes and methods instead of raw SQL. In this blog, we’ll explore how Django ORM makes database operations like CRUD (Create, Read, Update, Delete) simpler, cleaner, and more efficient.


1. What is an ORM?

An Object Relational Mapper (ORM) is a tool that bridges the gap between relational databases (like SQLite, PostgreSQL, MySQL) and object-oriented programming in Python.

Instead of writing:

SELECT * FROM students WHERE id=1;

You write:

Student.objects.get(id=1)

This abstraction makes code more readable, maintainable, and secure.

At CuriosityTech, we teach Django ORM as a must-have skill because most real-world companies prefer ORM over raw SQL for day-to-day operations.


2. Defining Models in Django

Models are Python classes that represent database tables.

Example – Creating a Student Model (models.py):

from django.db import models

class Student(models.Model):

    name = models.CharField(max_length=100)

    email = models.EmailField(unique=True)

    enrolled_date = models.DateField(auto_now_add=True)

    def __str__(self):

        return self.name

Here:

  • Each attribute = a column in the database.

  • CharField, EmailField, DateField = Django’s field types.


3. Migrating Models to Database

After defining a model, run:

python manage.py makemigrations

python manage.py migrate

This generates SQL commands behind the scenes and applies them to your database.


4. CRUD Operations with Django ORM

Create

student = Student.objects.create(name=”Riya”, email=”riya@curiositytech.in”)

Read

# Get all students

students = Student.objects.all()

# Get by ID

student = Student.objects.get(id=1)

Update

student = Student.objects.get(id=1)

student.name = “Riya Sharma”

student.save()

Delete

student = Student.objects.get(id=1)

student.delete()


5. Filtering and QuerySets

Django ORM allows powerful filtering:

# Students with name starting with ‘A’

students = Student.objects.filter(name__startswith=’A’)

# Students enrolled after 2024

students = Student.objects.filter(enrolled_date__year__gte=2024)

Chaining filters:

students = Student.objects.filter(name__startswith=’A’).exclude(email__icontains=’gmail.com’)


6. ORM vs Raw SQL – Comparison Table

OperationSQL StatementDjango ORM Code
Insert StudentINSERT INTO students …Student.objects.create(…)
Select All StudentsSELECT * FROM students;Student.objects.all()
Update Student NameUPDATE students SET name=’Riya’ WHERE id=1student.name = “Riya”; student.save()
Delete StudentDELETE FROM students WHERE id=1;student.delete()

8. Advantages of Using Django ORM

  • Faster Development → No need to manually write SQL.

  • Database Portability → Easily switch between SQLite, PostgreSQL, MySQL.

  • Security → Prevents SQL injection.

  • Readability → Pythonic code, easier for teams to understand.


9. Real-World Abstraction

Think of ORM as a translator:

  • You (developer) → Speak Python.

  • Database → Speaks SQL.

  • ORM → Acts as the interpreter so both sides understand each other seamlessly.

At CuriosityTech, we encourage learners to practice both ORM and raw SQL. Why? Because while ORM covers 80% of your work, knowing SQL helps you debug performance bottlenecks.


11. CuriosityTech Insight

Students often build a Student Management System or a Library Management App in Django at CuriosityTech. These projects prove their ORM skills because every feature — adding users, retrieving records, updating details — runs through Django ORM. Recruiters notice such projects instantly.


12. Conclusion

Django ORM is one of the reasons why Django is loved by full stack developers. It simplifies database operations and reduces boilerplate code while keeping applications secure and scalable. By practicing ORM regularly, you’ll save hours of coding and ensure that your apps are clean, maintainable, and production-ready.

Leave a Comment

Your email address will not be published. Required fields are marked *