| name | django-patterns |
| description | Django architecture patterns, DRF REST APIs, ORM best practices, caching, signals, and middleware. Use when building Django apps, designing DRF endpoints, optimizing querysets, or structuring Django projects. |
| origin | MCC |
Django Development Patterns
Production-grade Django architecture patterns for scalable, maintainable applications.
When to Activate
- Building Django web applications
- Designing Django REST Framework APIs
- Working with Django ORM and models
- Setting up Django project structure
- Implementing caching, signals, middleware
Project Structure
Recommended Layout
myproject/
├── config/
│ ├── __init__.py
│ ├── settings/
│ │ ├── __init__.py
│ │ ├── base.py # Base settings
│ │ ├── development.py # Dev settings
│ │ ├── production.py # Production settings
│ │ └── test.py # Test settings
│ ├── urls.py
│ ├── wsgi.py
│ └── asgi.py
├── manage.py
└── apps/
├── __init__.py
├── users/
│ ├── __init__.py
│ ├── models.py
│ ├── views.py
│ ├── serializers.py
│ ├── urls.py
│ ├── permissions.py
│ ├── filters.py
│ ├── services.py
│ └── tests/
└── products/
└── ...
Split Settings Pattern
from pathlib import Path
BASE_DIR = Path(__file__).resolve().parent.parent.parent
SECRET_KEY = env('DJANGO_SECRET_KEY')
DEBUG = False
ALLOWED_HOSTS = []
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'rest_framework',
'rest_framework.authtoken',
'corsheaders',
'apps.users',
'apps.products',
]
from .base import *
DEBUG = True
ALLOWED_HOSTS = ['localhost', '127.0.0.1']
INSTALLED_APPS += ['debug_toolbar']
EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'
from .base import *
DEBUG = False
ALLOWED_HOSTS = env.list('ALLOWED_HOSTS')
SECURE_SSL_REDIRECT = True
SESSION_COOKIE_SECURE = True
CSRF_COOKIE_SECURE = True
SECURE_HSTS_SECONDS = 31536000
Model Design Patterns
Model Best Practices
from django.db import models
from django.contrib.auth.models import AbstractUser
from django.core.validators import MinValueValidator
class User(AbstractUser):
"""Custom user model extending AbstractUser."""
email = models.EmailField(unique=True)
phone = models.CharField(max_length=20, blank=True)
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['username']
class Meta:
db_table = 'users'
ordering = ['-date_joined']
def __str__(self):
return self.email
class Product(models.Model):
"""Product model with proper field configuration."""
name = models.CharField(max_length=200)
slug = models.SlugField(unique=True, max_length=250)
description = models.TextField(blank=True)
price = models.DecimalField(
max_digits=10, decimal_places=2,
validators=[MinValueValidator(0)]
)
stock = models.PositiveIntegerField(default=0)
is_active = models.BooleanField(default=True)
category = models.ForeignKey(
'Category', on_delete=models.CASCADE, related_name='products'
)
tags = models.ManyToManyField('Tag', blank=True, related_name='products')
created_at = models.DateTimeField(auto_now_add=)
updated_at = models.DateTimeField(auto_now=)
:
db_table =
ordering = []
indexes = [
models.Index(fields=[]),
models.Index(fields=[]),
models.Index(fields=[, ]),
]
constraints = [
models.CheckConstraint(
check=models.Q(price__gte=),
name=
)
]
():
.name
Service Layer Pattern
from django.db import transaction
from .models import Order, OrderItem
class OrderService:
"""Service layer for order-related business logic."""
@staticmethod
@transaction.atomic
def create_order(user, cart: Cart) -> Order:
"""Create order from cart."""
order = Order.objects.create(user=user, total_price=cart.total_price)
for item in cart.items.all():
OrderItem.objects.create(
order=order, product=item.product,
quantity=item.quantity, price=item.product.price
)
cart.items.all().delete()
return order
@staticmethod
def process_payment(order: Order, payment_data: dict) -> bool:
"""Process payment for order."""
payment = PaymentGateway.charge(
amount=order.total_price, token=payment_data['token']
)
if payment.success:
order.status = Order.Status.PAID
order.save()
OrderService.send_confirmation_email(order)
return True
return False
Django REST Framework Patterns
For detailed DRF serializer, viewset, and custom action examples, see drf-examples.md.
Key patterns:
- Serializer per action: Use
get_serializer_class() to return different serializers for create vs read
- ViewSet with filters: Combine
DjangoFilterBackend, SearchFilter, OrderingFilter
- Custom actions: Use
@action decorator for non-CRUD endpoints
- Validation: Field-level with
validate_<field>() and object-level with validate()
ORM, Caching, Signals, and Middleware
For detailed examples of QuerySets, managers, caching strategies, signals, middleware, and performance optimization, see orm-and-middleware.md.
Key patterns:
- Custom QuerySet: Chain
.active().with_category().in_stock()
- N+1 prevention:
select_related for FK, prefetch_related for M2M
- Low-level caching:
cache.get(key) / cache.set(key, value, timeout)
- Signals:
post_save for profile creation, register in AppConfig.ready()
- Bulk operations:
bulk_create, bulk_update for batch processing
Quick Reference
| Pattern | Description |
|---|
| Split settings | Separate dev/prod/test settings |
| Custom QuerySet | Reusable query methods |
| Service Layer | Business logic separation |
| ViewSet | REST API endpoints |
| Serializer validation | Request/response transformation |
| select_related | Foreign key optimization |
| prefetch_related | Many-to-many optimization |
| Cache first | Cache expensive operations |
| Signals | Event-driven actions |
| Middleware | Request/response processing |
Remember: Django provides many shortcuts, but for production applications, structure and organization matter more than concise code. Build for maintainability.
Reference Files