Introduction to ORM in Django
When building web applications, working with databases is essential — but writing raw SQL for every operation can be tedious and error-prone. Django’s Object-Relational Mapping (ORM) offers a powerful way to interact with databases using Python code instead of SQL, simplifying development and improving productivity.
What is an ORM?
An Object-Relational Mapper (ORM) is a tool that maps database tables to programming language objects. In Django, each table corresponds to a Python class (a model), and each column is represented by a class attribute. This abstraction lets you work with familiar Python syntax while Django handles SQL queries behind the scenes.
Why use Django ORM?
✅ Ease of use — Perform complex database operations using simple Python methods.
✅ Database-agnostic — Switch between databases (like PostgreSQL, MySQL, SQLite) with minimal changes.
✅ Security — Protects against SQL injection by safely constructing queries.
✅ Productivity — Reduces boilerplate code and speeds up development.
Defining models
In Django, you define models in your app’s models.py file. Here’s an example of a simple Book model:
from django.db import models
class Book(models.Model):
title = models.CharField(max_length=200)
author = models.CharField(max_length=100)
published_date = models.DateField()
price = models.DecimalField(max_digits=6, decimal_places=2)
def __str__(self):
return f"{self.title} by {self.author}"
Once defined, run python manage.py makemigrations and python manage.py migrate to create the corresponding database table.
Basic CRUD with Django ORM
✅ Create
book = Book.objects.create(title="Django Basics", author="Jane Doe", published_date="2023-01-01", price=29.99)
✅ Read
all_books = Book.objects.all()
book = Book.objects.get(id=1)
✅ Update
book.title = "Advanced Django"
book.save()
✅ Delete
book.delete()
Querying with filters
The ORM supports powerful queries with filter(), exclude(), and chaining:
recent_books = Book.objects.filter(published_date__year=2023)
affordable_books = Book.objects.filter(price__lt=50)
Conclusion
Django’s ORM is one of its greatest strengths, allowing you to manage data intuitively and securely with Python objects. By mastering the ORM, you can build robust, database-driven web applications faster and with fewer bugs.
Learn Fullstack Python Training Course
Read More:
Django REST Framework Tutorial
PostgreSQL Integration with Django
Visit Quality Thought Training Institute
Comments
Post a Comment