django-patterns
Skill3 starsChanged 8 months agoMITView on GitHub
Django 5.x best practices. Covers ORM optimization, class-based views, middleware, Django REST Framework, signals, and deployment patterns. Use when building Django applications or reviewing Django code.
19 other projects use a version of this.
Adopted by
Most recently taken up by
- ku5ic/claude-kittheir own version, first seen Oct 6, 2026
- templetongroup/radianttheir own version, first seen Sep 17, 2026
- theyoungastronauts/polaristheir own version, first seen Aug 3, 2026
- SamuelNDCE/claude-super-skill-librarytheir own version, first seen Aug 1, 2026
- JunMystery/Agent-Guidance-Pythontheir own version, first seen Jul 21, 2026
- Lukasbrujula/claude-code-frameworktheir own version, first seen Jul 6, 2026
Used with
Projects with it also use springboot-verification, jpa-patterns and 3 more.
Other files people use alongside this one.
Files found in the same public projects as a version of this one, more often than they turn up anywhere else. Each project counts once, large collections count for less, and this file's own repository is left out.
FaisalAlqarniSkillspringboot-verification
Verification loop for Spring Boot projects: build, static analysis, tests with coverage, security scans, and diff review before release or PR.
Also in 5 projects that use this
FaisalAlqarniSkilljpa-patterns
JPA/Hibernate patterns for entity design, relationships, query optimization, transactions, auditing, indexing, pagination, and pooling in Spring Boot.
Also in 7 projects that use this
yanhaoluo0Skilljava-coding-standards
阿里巴巴Java开发手册编程规约,包含命名风格、常量定义、代码格式、OOP规约、日期时间、集合处理、并发处理、控制语句、注释规约等。Use when writing Java code, reviewing code, or following Alibaba Java coding standards.
Also in 7 projects that use this
WorldFlowAISkillclickhouse-io
ClickHouse database patterns, query optimization, analytics, and data engineering best practices for high-performance analytical workloads.
Also in 7 projects that use this
InfopibeSkillswift-protocol-di-testing
Protocol-based dependency injection for testable Swift code — mock file system, network, and external APIs using focused protocols and Swift Testing.
Also in 4 projects that use this
Other versions19 projects use a version of this.
Word for word · 0
None found.
Edited · 0
None found.
Wrote their own version · 19
- rohitg00/awesome-claude-code-toolkit★ 2.7ksame name
- xu-xiang/everything-claude-code-zh★ 2ksame name
- loulanyue/awesome-claude-notes★ 272same name
- tpavanipradeep/everything-claude-code★ 134same name
- templetongroup/radiant★ 113same name
- Jamkris/everything-gemini-code★ 87same name
- tranhieutt/software_development_department★ 72same name
- codelably/harmony-claude-code★ 43same name
- skateddu/claude-code-python-setup★ 28same name
- FaisalAlqarni/sp-ecc★ 9same name
9 more not listed
How matches are found. Word for word: the exact same text. Edited: shares passages with this file (“99% same” means 99% of its five-word phrases also appear here; 10% or more counts). Their own version: similar meaning, or, weakest, the same name. We can’t tell which project had it first. Projects are counted among the 200 most-starred candidates, and mentions are links to the repository we found, up to 50 per site, so both counts are a floor.
In this repository72 other files it gives its agents.
- AGENTS.mdAGENTS.md
- CLAUDE.mdCLAUDE.md
- llms.txtllms.txt
- api-designerSkill
- backend-patternsSkill
- code-reviewerSkill
- debugging-assistantSkill
- golang-testingSkill
- project-guidelines-exampleSkill
- python-testingSkill
- refactoring-guideSkill
- spec-driven-developmentSkill
- tdd-workflowSkill
- verification-loopSkill
- update-docsSkill
- api-docsSkill
- changelog-writerSkill
- readme-generatorSkill
- django-securitySkill
- django-tddSkill
- django-verificationSkill
- fastapi-patternsSkill
- nextjs-patternsSkill
- react-patternsSkill
- springboot-patternsSkill
- springboot-securitySkill
- springboot-tddSkill
- branch-strategySkill
- changelogSkill
- commit-helperSkill
- pr-creatorSkill
- prSkill
- evolveSkill
- instinct-exportSkill
- instinct-importSkill
- instinct-statusSkill
- cleanupSkill
- lint-fixSkill
- refactor-cleanSkill
- update-depsSkill
- continuous-learningSkill
- continuous-learning-v2Skill
- eval-harnessSkill
- iterative-retrievalSkill
- strategic-compactSkill
- golang-patternsSkill
- python-patternsSkill
- rust-patternsSkill
- typescript-patternsSkill
- accessibility-checkerSkill
- build-fixSkill
- code-reviewSkill
- e2eSkill
- performance-reviewerSkill
- security-auditorSkill
- security-reviewSkill
- test-coverageSkill
- checkpointSkill
- deploySkill
- evalSkill
- The first 60 shown.
The file
Files
Django Patterns
Modern Django 5.x patterns and best practices.
Project Structure
project/
├── config/ # Project settings (renamed from project/)
│ ├── settings/
│ │ ├── base.py # Shared settings
│ │ ├── development.py # Dev overrides
│ │ └── production.py # Prod overrides
│ ├── urls.py
│ └── wsgi.py
├── apps/
│ └── users/
│ ├── models.py
│ ├── views.py
│ ├── serializers.py # DRF serializers
│ ├── urls.py
│ ├── services.py # Business logic
│ ├── selectors.py # Complex queries
│ └── tests/
│ ├── test_models.py
│ ├── test_views.py
│ └── factories.py
└── manage.pyORM Optimization
Select Related (FK joins)
# Bad: N+1 queries
users = User.objects.all()
for user in users:
print(user.profile.bio) # Extra query per user
# Good: Single JOIN query
users = User.objects.select_related("profile").all()Prefetch Related (M2M and reverse FK)
# Bad: N+1 queries for many-to-many
articles = Article.objects.all()
for article in articles:
print(article.tags.all()) # Extra query per article
# Good: Two queries total (articles + tags)
articles = Article.objects.prefetch_related("tags").all()Only/Defer for Partial Loading
# Load only needed fields
users = User.objects.only("id", "name", "email")
# Exclude heavy fields
articles = Article.objects.defer("body", "raw_html")Efficient Bulk Operations
# Bulk create (single INSERT)
User.objects.bulk_create([
User(name="Alice", email="alice@example.com"),
User(name="Bob", email="bob@example.com"),
], batch_size=1000)
# Bulk update (single UPDATE)
User.objects.filter(is_active=False).update(is_active=True)
# F() expressions for atomic updates
from django.db.models import F
Product.objects.filter(id=product_id).update(stock=F("stock") - 1)Custom QuerySet Managers
class ArticleQuerySet(models.QuerySet):
def published(self):
return self.filter(status="published", published_at__lte=timezone.now())
def by_author(self, user):
return self.filter(author=user)
class Article(models.Model):
objects = ArticleQuerySet.as_manager()
# Chain: Article.objects.published().by_author(user)Views
Class-Based Views (Generic)
from django.views.generic import ListView, DetailView, CreateView
class ArticleListView(ListView):
model = Article
queryset = Article.objects.published().select_related("author")
paginate_by = 20
template_name = "articles/list.html"Django REST Framework ViewSets
from rest_framework import viewsets, permissions, status
from rest_framework.decorators import action
from rest_framework.response import Response
class UserViewSet(viewsets.ModelViewSet):
queryset = User.objects.all()
serializer_class = UserSerializer
permission_classes = [permissions.IsAuthenticated]
def get_queryset(self):
return super().get_queryset().filter(is_active=True)
@action(detail=True, methods=["post"])
def deactivate(self, request, pk=None):
user = self.get_object()
user.is_active = False
user.save(update_fields=["is_active"])
return Response(status=status.HTTP_204_NO_CONTENT)DRF Serializers
from rest_framework import serializers
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = ["id", "name", "email", "created_at"]
read_only_fields = ["id", "created_at"]
def validate_email(self, value):
if User.objects.filter(email=value).exclude(pk=self.instance and self.instance.pk).exists():
raise serializers.ValidationError("Email already in use.")
return valueService Layer
# apps/users/services.py
from django.db import transaction
class UserService:
@staticmethod
@transaction.atomic
def create_user(*, name: str, email: str, role: str = "viewer") -> User:
user = User.objects.create(name=name, email=email, role=role)
Profile.objects.create(user=user)
AuditLog.objects.create(action="user_created", target_id=user.id)
return userMiddleware
import time
import logging
logger = logging.getLogger(__name__)
class RequestTimingMiddleware:
def __init__(self, get_response):
self.get_response = get_response
def __call__(self, request):
start = time.perf_counter()
response = self.get_response(request)
elapsed = time.perf_counter() - start
logger.info("%s %s %.4fs", request.method, request.path, elapsed)
response["X-Process-Time"] = f"{elapsed:.4f}"
return responseSignals (Use Sparingly)
from django.db.models.signals import post_save
from django.dispatch import receiver
@receiver(post_save, sender=User)
def create_user_profile(sender, instance, created, **kwargs):
if created:
Profile.objects.create(user=instance)Prefer service layer over signals — signals create hidden coupling and are difficult to debug. Use signals only for cross-app decoupling where direct imports would create circular dependencies.
Model Best Practices
import uuid
from django.db import models
class TimeStampedModel(models.Model):
"""Abstract base with UUID primary key and timestamps."""
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
class Meta:
abstract = True
class User(TimeStampedModel):
name = models.CharField(max_length=100)
email = models.EmailField(unique=True)
is_active = models.BooleanField(default=True)
class Meta:
ordering = ["-created_at"]
indexes = [
models.Index(fields=["email"]),
models.Index(fields=["is_active", "-created_at"]),
]
def __str__(self):
return self.nameTesting
import pytest
from django.test import TestCase
from rest_framework.test import APIClient
class TestUserAPI(TestCase):
def setUp(self):
self.client = APIClient()
self.user = User.objects.create(name="Test", email="test@example.com")
self.client.force_authenticate(user=self.user)
def test_list_users(self):
response = self.client.get("/api/users/")
self.assertEqual(response.status_code, 200)
self.assertEqual(len(response.data["results"]), 1)
def test_create_user(self):
response = self.client.post("/api/users/", {"name": "New", "email": "new@example.com"})
self.assertEqual(response.status_code, 201)Factory Pattern (factory_boy)
import factory
class UserFactory(factory.django.DjangoModelFactory):
class Meta:
model = User
name = factory.Faker("name")
email = factory.LazyAttribute(lambda o: f"{o.name.lower().replace(' ', '.')}@example.com")
is_active = TrueChecklist
select_relatedfor ForeignKey access in loopsprefetch_relatedfor ManyToMany access in loops- Business logic in service layer, not views
F()expressions for atomic field updatestransaction.atomicfor multi-model writes- Custom QuerySet managers for reusable filters
- UUID primary keys for public-facing IDs
- Abstract TimeStampedModel base class
- Database indexes on filtered/sorted fields
- Tests use
force_authenticateor factory patterns
Does it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
No reviews yet
People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.
- It worked
- Partly
- It didn't
Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.
Your trail
Files you open will collect here, so you can find them again.
Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.
Now do this for your own.
Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.

