Using Django ORM to Interact with Databases

 Using Django ORM to Interact with Databases

Django ORM (Object-Relational Mapping) is a powerful feature of the Django web framework that lets you interact with your database using Python code instead of writing raw SQL queries. It provides an easy, readable, and efficient way to create, retrieve, update, and delete records.


What is Django ORM?

ORM stands for Object-Relational Mapping.


It translates Python classes (called models) into database tables.


You work with Python objects instead of writing SQL.


Supports multiple databases like SQLite, PostgreSQL, MySQL, and Oracle.


Key Concepts

1. Models

Models are Python classes that define the structure of your database tables.


python

Copy

Edit

from django.db import models


class Book(models.Model):

    title = models.CharField(max_length=100)

    author = models.CharField(max_length=50)

    published_date = models.DateField()

    pages = models.IntegerField()


    def __str__(self):

        return self.title

Each attribute corresponds to a database column.


Django automatically creates the table and columns based on your model.


2. Migrations

After defining or changing models, run:


bash

Copy

Edit

python manage.py makemigrations

python manage.py migrate

This creates or updates database tables to match your models.


Basic Database Operations with Django ORM

Creating Records

python

Copy

Edit

book = Book(title="Django for Beginners", author="John Doe", published_date="2023-01-01", pages=250)

book.save()  # Saves the record in the database

Or more simply:


python

Copy

Edit

Book.objects.create(title="Django ORM Guide", author="Jane Smith", published_date="2022-06-15", pages=300)

Retrieving Records

Get all books:


python

Copy

Edit

books = Book.objects.all()

Filter books by author:


python

Copy

Edit

django_books = Book.objects.filter(author="John Doe")

Get a single record by primary key:


python

Copy

Edit

book = Book.objects.get(id=1)

Updating Records

python

Copy

Edit

book = Book.objects.get(id=1)

book.pages = 275

book.save()

Or update multiple records:


python

Copy

Edit

Book.objects.filter(author="John Doe").update(pages=300)

Deleting Records

python

Copy

Edit

book = Book.objects.get(id=1)

book.delete()

Or delete multiple records:


python

Copy

Edit

Book.objects.filter(author="Jane Smith").delete()

Advanced Querying

Ordering:


python

Copy

Edit

books = Book.objects.order_by('published_date')

Chaining filters:


python

Copy

Edit

books = Book.objects.filter(author="John Doe").exclude(pages__lt=100)

Aggregation:


python

Copy

Edit

from django.db.models import Avg


average_pages = Book.objects.aggregate(Avg('pages'))

Why Use Django ORM?

Simplicity: Write database queries using Python, not SQL.


Database Abstraction: Easily switch databases without changing your code.


Security: Protects against SQL injection automatically.


Productivity: Handles complex queries with readable code.

Learn Full Stack Python Course in Hyderabad

Read More

How to Connect Python with SQL Databases

Setting Up PostgreSQL for Full Stack Python Projects

SQL vs NoSQL: What’s Best for Full Stack Python Development?

Introduction to Databases for Full Stack Python Development

Visit Our IHUB Talent Training Institute in Hyderabad

Get Directions

Comments

Popular posts from this blog

How to Install and Set Up Selenium in Python (Step-by-Step)

Feeling Stuck in Manual Testing? Here’s Why You Should Learn Automation Testing

A Beginner's Guide to ETL Testing: What You Need to Know