agentleFS
tranhieutttranhieutt/software_development_department/.claude/skills/django-patterns/SKILL.md

django-patterns

Skill72 starsChanged 7 months agoMITView on GitHub

19 other projects use a version of this.

Adopted by

Most recently taken up by

Used with

Projects with it also use django-verification, springboot-tdd and 10 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.
  • FaisalAlqarniSkill

    django-verification

    Verification loop for Django projects: migrations, linting, tests with coverage, security scans, and deployment readiness checks before release or PR.

    Also in 9 projects that use this

  • FaisalAlqarniSkill

    springboot-tdd

    Test-driven development for Spring Boot using JUnit 5, Mockito, MockMvc, Testcontainers, and JaCoCo. Use when adding features, fixing bugs, or refactoring.

    Also in 8 projects that use this

  • johnrtiptonSkill

    django-security

    This skill should be used when conducting security reviews, auditing Django applications, hardening security settings, implementing OWASP Top 10 protections, managing secrets, or ensuring multi-tenant security isolation. Provides automated security auditor that scans settings, code, dependencies, and multi-tenant configurations with auto-fix capabilities.

    Also in 9 projects that use this

  • yanhaoluo0Skill

    java-coding-standards

    阿里巴巴Java开发手册编程规约,包含命名风格、常量定义、代码格式、OOP规约、日期时间、集合处理、并发处理、控制语句、注释规约等。Use when writing Java code, reviewing code, or following Alibaba Java coding standards.

    Also in 7 projects that use this

  • joneqianSkill

    continuous-learning-v2

    Instinct-based learning system that observes sessions via hooks, creates atomic instincts with confidence scoring, and evolves them into skills/commands/agents.

    Also in 8 projects that use this

  • WorldFlowAISkill

    clickhouse-io

    ClickHouse database patterns, query optimization, analytics, and data engineering best practices for high-performance analytical workloads.

    Also in 7 projects that use this

  • +4 more from FaisalAlqarni

The file

We split this skill into the rules it gives an agent

2 rules. About 0 are common, 0 are distinctive, and 2 are very specific to this project.

  • ≈0

    Common · estimate

    Many files like this have a rule of this kind.

  • ≈0

    Distinctive · estimate

    This author's own choices. Worth a look.

  • 2

    Very specific

    Tied to their project's names, files or tools. Probably skip.

  • Common
  • Distinctive
  • Very specific
  1. Very specific:

    N+1 queries: always use select_related (FK) / prefetch_related (M2M) — never iterate and query inside loops

    line 22
  2. Very specific:

    Migrations on large tables: use RunSQL with CONCURRENTLY index creation to avoid locks

    line 26

≈ “Common” is an estimate: at least 1 in 5 of the 213,897 skill files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.

Keep what fits and drop the rest. Your version, ready for your agents.
Files
SKILL.md

Django & DRF Professional Patterns

Core Expertise

  • Modern Django: 5.x features, async views/middleware, ASGI deployment.
  • Background & Real-time: Celery integration, Django Channels.
  • ORM Optimization: select_related, prefetch_related, custom managers.
  • Security: JWT auth, OAuth2, RBAC, protection against SQLi/XSS/CSRF.

Critical rules (non-obvious)

  • N+1 queries: always use select_related (FK) / prefetch_related (M2M) — never iterate and query inside loops
  • get_or_create race condition: wrap in transaction.atomic() in concurrent environments
  • Never call save() inside pre_save signal — causes infinite recursion; use update_fields
  • bulk_create skips signals and save() — don't use when signal logic is required
  • Migrations on large tables: use RunSQL with CONCURRENTLY index creation to avoid locks

ORM: select_related vs prefetch_related

# FK / OneToOne → select_related (JOIN)
books = Book.objects.select_related("author", "author__publisher").all()

# M2M / reverse FK → prefetch_related (separate query)
authors = Author.objects.prefetch_related("books", "books__tags").all()

# Custom prefetch with queryset
from django.db.models import Prefetch
Author.objects.prefetch_related(
    Prefetch("books", queryset=Book.objects.filter(published=True), to_attr="active_books")
)

ORM: annotations and aggregations

from django.db.models import Count, Avg, Q, F, Value
from django.db.models.functions import Coalesce

Author.objects.annotate(
    book_count=Count("books"),
    avg_rating=Coalesce(Avg("books__rating"), Value(0.0)),
    high_rated=Count("books", filter=Q(books__rating__gte=4)),
).filter(book_count__gt=0).order_by("-book_count")

ORM: F expressions (avoid race conditions)

# BAD — race condition
product = Product.objects.get(pk=pk)
product.stock -= quantity
product.save()

# GOOD — atomic at DB level
Product.objects.filter(pk=pk).update(stock=F("stock") - quantity)

Views: class-based view pattern

from django.views import View
from django.contrib.auth.mixins import LoginRequiredMixin

class OrderDetailView(LoginRequiredMixin, View):
    def get(self, request, pk):
        order = get_object_or_404(Order.objects.select_related("user"), pk=pk, user=request.user)
        return JsonResponse(OrderSerializer(order).data)

DRF: serializer with validation

class ProductSerializer(serializers.ModelSerializer):
    class Meta:
        model = Product
        fields = ["id", "name", "price", "stock"]
        read_only_fields = ["id"]

    def validate_price(self, value):
        if value <= 0:
            raise serializers.ValidationError("Price must be positive.")
        return value

    def validate(self, data):  # cross-field
        if data["stock"] == 0 and data.get("is_featured"):
            raise serializers.ValidationError("Out-of-stock products cannot be featured.")
        return data

DRF: ViewSet with custom actions

from rest_framework import viewsets, status
from rest_framework.decorators import action
from rest_framework.response import Response

class ProductViewSet(viewsets.ModelViewSet):
    queryset = Product.objects.select_related("category")
    serializer_class = ProductSerializer
    permission_classes = [IsAuthenticated]

    @action(detail=True, methods=["post"], url_path="archive")
    def archive(self, request, pk=None):
        product = self.get_object()
        product.is_archived = True
        product.save(update_fields=["is_archived"])
        return Response(status=status.HTTP_204_NO_CONTENT)

DRF: filtering + pagination

# settings.py
REST_FRAMEWORK = {
    "DEFAULT_FILTER_BACKENDS": ["django_filters.rest_framework.DjangoFilterBackend"],
    "DEFAULT_PAGINATION_CLASS": "rest_framework.pagination.CursorPagination",
    "PAGE_SIZE": 20,
}

# viewset
class ProductViewSet(viewsets.ReadOnlyModelViewSet):
    filterset_fields = {"price": ["gte", "lte"], "category": ["exact"]}
    ordering_fields = ["price", "created_at"]
    search_fields = ["name", "description"]

Celery task pattern

from celery import shared_task
from django.db import transaction

@shared_task(bind=True, max_retries=3, default_retry_delay=60)
def send_order_email(self, order_id: int):
    try:
        order = Order.objects.select_related("user").get(pk=order_id)
        send_email(order.user.email, order)
    except Order.DoesNotExist:
        return  # don't retry if deleted
    except Exception as exc:
        raise self.retry(exc=exc)

# Dispatch after DB commit — avoids race condition
def create_order(data):
    with transaction.atomic():
        order = Order.objects.create(**data)
        transaction.on_commit(lambda: send_order_email.delay(order.pk))

Common pitfalls

PitfallFix
N+1 queries in serializerselect_related / prefetch_related on queryset
objects.all() in viewsAlways filter + limit; never expose unbounded querysets
Storing secrets in settings.pyUse django-environ or environment variables
DateTimeField(auto_now_add=True) not testableUse default=timezone.now for overridable defaults
Sync ORM in async viewsUse sync_to_async or Django 4.1+ async ORM

Download now (ZIP)

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
What did you use it for? e.g. Reviewing pull requests in a Rails app

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.