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.
Django models are Python classes that inherit from models.Model. Django automatically converts them into database tables.
# 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()
# 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)
# Update existing product
from myapp.models import Product
product = Product.objects.get(id=1)
product.price = 1099.99
product.stock = 8
product.save()
# Delete a product
from myapp.models import Product
product = Product.objects.get(id=1)
product.delete()
save()all(), get(), filter()save()delete()Imagine the ORM as a bridge converting Python instructions into SQL queries automatically. Try interacting with the virtual database below:
| ID | Name | Price ($) | Stock |
|---|
filter() for multiple resultsDoesNotExist exceptions