← Back to Chapters

Using Django ORM to Interact with Database

?️ Using Django ORM to Interact with Database

? Quick Overview

The Django ORM (Object-Relational Mapping) allows you to interact with your database using Python objects instead of raw SQL. It simplifies database operations such as creating, reading, updating, and deleting records.

? Key Concepts

  • Models represent database tables
  • Objects map to table rows
  • ORM abstracts SQL complexity

? Syntax / Theory

Django models are Python classes that inherit from models.Model. Django automatically converts them into database tables.

➕ Creating Records

? View Code Example
# Import Product model
from myapp.models import Product
# Create and save a new product
product = Product(name="Laptop", price=999.99, stock=10)
product.save()

? Reading Records

? View Code Example
# Fetch records using Django ORM
from myapp.models import Product
products = Product.objects.all()
product = Product.objects.get(id=1)
filtered_products = Product.objects.filter(price__gte=500)

✏️ Updating Records

? View Code Example
# Update existing product
from myapp.models import Product
product = Product.objects.get(id=1)
product.price = 1099.99
product.stock = 8
product.save()

?️ Deleting Records

? View Code Example
# Delete a product
from myapp.models import Product
product = Product.objects.get(id=1)
product.delete()

? Explanation

  • Create: Use save()
  • Read: Use all(), get(), filter()
  • Update: Modify fields and call save()
  • Delete: Call delete()

? Interactive Example

Imagine the ORM as a bridge converting Python instructions into SQL queries automatically. Try interacting with the virtual database below:

ID Name Price ($) Stock
Waiting for command...

? Use Cases

  • CRUD web applications
  • Admin dashboards
  • API backends

✅ Tips & Best Practices

  • Use filter() for multiple results
  • Handle DoesNotExist exceptions
  • Use bulk operations for performance

? Try It Yourself

  • Create a model with 3 fields
  • Perform CRUD operations
  • Experiment with filters