All skills
jeffallan avatar

/django-expert

@2bb8261
by jeffallanjeffallan/claude-skills12k stars
1,127

Use when building Django web applications or REST APIs with Django REST Framework. Invoke when working with settings.py, models.py, manage.py, or any Django project file. Creates Django models with proper indexes, optimizes ORM queries using select_related/prefetch_related, builds DRF serializers and viewsets, and configures JWT authentication. Trigger terms: Django, DRF, Django REST Framework, Django ORM, Django model, serializer, viewset, Python web.

Use this Skill: https://skilld.dev/gh/jeffallan/claude-skills/django-expert

This session only. Nothing lands on disk.

referencesmodels-orm.md

≈972 tokens on demand. Your agent reads this file only when SKILL.md points to it.

Models & ORM

Model Design

from django.db import models
from django.contrib.auth.models import AbstractUser

class User(AbstractUser):
    email = models.EmailField(unique=True)
    bio = models.TextField(blank=True)
    avatar = models.ImageField(upload_to='avatars/', blank=True)

    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = ['username']

    class Meta:
        indexes = [models.Index(fields=['email'])]

class Product(models.Model):
    name = models.CharField(max_length=200, db_index=True)
    slug = models.SlugField(unique=True)
    description = models.TextField()
    price = models.DecimalField(max_digits=10, decimal_places=2)
    stock = models.PositiveIntegerField(default=0)
    is_active = models.BooleanField(default=True)

    category = models.ForeignKey(
        'Category', on_delete=models.SET_NULL,
        null=True, related_name='products'
    )
    tags = models.ManyToManyField('Tag', related_name='products', blank=True)
    created_by = models.ForeignKey(
        User, on_delete=models.CASCADE, related_name='products'
    )
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        ordering = ['-created_at']
        indexes = [
            models.Index(fields=['slug']),
            models.Index(fields=['is_active', '-created_at']),
        ]

    def __str__(self) -> str:
        return self.name

Query Optimization

# ❌ N+1 Problem
for product in Product.objects.all():
    print(product.category.name)  # Query per product

# ✅ select_related (ForeignKey, OneToOne)
products = Product.objects.select_related('category', 'created_by').all()

# ✅ prefetch_related (ManyToMany, reverse FK)
products = Product.objects.prefetch_related('tags').all()

# Combined
products = Product.objects.select_related(
    'category', 'created_by'
).prefetch_related('tags').all()

Efficient Queries

# Only fetch needed fields
users = User.objects.only('id', 'email').all()
users = User.objects.defer('bio', 'avatar').all()

# Aggregations
from django.db.models import Count, Avg, Sum, F, Q

Product.objects.aggregate(
    avg_price=Avg('price'),
    total_stock=Sum('stock'),
)

# Annotate with counts
categories = Category.objects.annotate(
    product_count=Count('products')
).filter(product_count__gt=0)

# F expressions (database-level operations)
Product.objects.update(price=F('price') * 1.1)  # 10% increase

# Q objects (complex queries)
Product.objects.filter(
    Q(price__lt=100) | Q(stock__gt=50),
    is_active=True
)

Custom Manager

class ProductManager(models.Manager):
    def active(self):
        return self.filter(is_active=True)

    def in_stock(self):
        return self.filter(stock__gt=0)

    def with_related(self):
        return self.select_related('category').prefetch_related('tags')

class Product(models.Model):
    # ... fields ...
    objects = ProductManager()

# Usage
Product.objects.active().in_stock().with_related()

Bulk Operations

# Bulk create
Product.objects.bulk_create([
    Product(name='A', price=10),
    Product(name='B', price=20),
], batch_size=1000)

# Bulk update
Product.objects.filter(category=old).update(category=new)

# Bulk update specific instances
products = list(Product.objects.filter(is_active=True))
for p in products:
    p.stock += 10
Product.objects.bulk_update(products, ['stock'], batch_size=1000)

Quick Reference

Method Use Case
select_related() FK, OneToOne
prefetch_related() ManyToMany, reverse FK
only() / defer() Partial field loading
annotate() Add computed fields
aggregate() Single-row aggregates
F() Database-level operations
Q() Complex queries
bulk_create() Mass insert
update() Mass update

Source: SKILL.md on GitHub

1 alert16d5 checks · Risk CRITICAL
  • Gen Agent Trust Hub16d

    A comprehensive Django and Django REST Framework development assistant. The skill promotes security best practices such as avoiding raw SQL, using environment variables for secrets, and implementing proper permissions. It has a low risk of indirect prompt injection because it is designed to analyze and process user-provided code files.

  • Socket16d

    No alerts

  • Snyk16d

    Risk: LOW · No issues

  • Runlayer6mo

    6 files scanned · No issues

  • ZeroLeaks5mo

    Score: 93/100 · 2 sections analyzed

Signed by skilld at 2bb8261. This ties the file your Agent reads to that commit on GitHub. It does not review the instructions.

Last checked against GitHub 2 months ago.

Steadyupdated 2 months ago
Other metadata
metadata
{
  "author": "https://github.com/Jeffallan",
  "version": "1.1.0",
  "domain": "backend",
  "triggers": "Django, DRF, Django REST Framework, Django ORM, Django model, serializer, viewset, Python web",
  "role": "specialist",
  "scope": "implementation",
  "output-format": "code",
  "related-skills": "fullstack-guardian, fastapi-expert, test-master, django-storages-s3"
}

README badge

README badge for jeffallan/claude-skills/django-expert

Builds Django REST Framework APIs and models with proper indexing, query optimization via select_related/prefetch_related, DRF serializers with validation, viewsets with permissions, and JWT authentication. Targets Django 5.0 projects and provides workflows for schema design, ORM optimization, and APITestCase testing.

Generated from the current SKILL.md.

Does this skill work with Django 4.x or only Django 5.0?
The skill is built around Django 5.0 and its async views. It may work with Django 4.x but is optimized for Django 5.0 features.
Does this cover Django REST Framework setup and serializers?
Yes. The skill includes DRF serializer design with validation, viewset implementation, and API endpoint configuration with proper permissions.
Does this skill handle authentication?
Yes. It covers JWT authentication via SimpleJWT, session authentication, and permission classes like IsAuthenticatedOrReadOnly.
Will this optimize my existing Django queries?
Yes. The skill emphasizes select_related and prefetch_related to prevent N+1 queries, and recommends database indexes on frequently queried fields.
Does this include testing guidance?
Yes. The skill covers APITestCase, fixtures, and factories for testing Django models and API endpoints, with a reference guide for pytest-django.

Generated from the current SKILL.md. These answers refresh after source changes.