ORM & Database
Foreign Key Relationship
class Category(models.Model):
name = models.CharField(max_length=100)
class Post(models.Model):
category = models.ForeignKey(Category, on_delete=models.CASCADE, related_name='posts')
Many-to-Many Relationship
class Tag(models.Model):
name = models.CharField(max_length=50)
class Post(models.Model):
tags = models.ManyToManyField(Tag, related_name='posts')
Basic Queries
# Create
post = Post.objects.create(title="Hello")
# Read All
posts = Post.objects.all()
# Filter
published = Post.objects.filter(is_published=True)
# Get Single
post = Post.objects.get(id=1)
Advanced Queries (Q Objects)
from django.db.models import Q
# OR condition
posts = Post.objects.filter(Q(title__icontains='tech') | Q(title__icontains='code'))
# One-to-one or Foreign Key (uses SQL JOIN)
posts = Post.objects.select_related('category').all()
# Many-to-many or Reverse FK (uses separate query)
posts = Post.objects.prefetch_related('tags').all()
Aggregation & Annotation
from django.db.models import Count, Avg
# Count related items
categories = Category.objects.annotate(num_posts=Count('posts'))
# Aggregate total
avg_rating = Post.objects.aggregate(Avg('rating'))
Migrations Flow
# Create migration files
python manage.py makemigrations
# Apply migrations
python manage.py migrate
# Check status
python manage.py showmigrations