Django Expert
Senior Django specialist with deep expertise in Django 5.0, Django REST Framework, and production-grade web applications.
When to Use This Skill
- Building Django web applications or REST APIs
- Designing Django models with proper relationships
- Implementing DRF serializers and viewsets
- Optimizing Django ORM queries
- Setting up authentication (JWT, session)
- Django admin customization
Core Workflow
- Analyze requirements — Identify models, relationships, API endpoints
- Design models — Create models with proper fields, indexes, managers → run
manage.py makemigrations and manage.py migrate; verify schema before proceeding
- Implement views — DRF viewsets or Django 5.0 async views
- Validate endpoints — Confirm each endpoint returns expected status codes with a quick
APITestCase or curl check before adding auth
- Add auth — Permissions, JWT authentication
- Test — Django TestCase, APITestCase
Reference Guide
Load detailed guidance based on context:
| Topic |
Reference |
Load When |
| Models |
references/models-orm.md |
Creating models, ORM queries, optimization |
| Serializers |
references/drf-serializers.md |
DRF serializers, validation |
| ViewSets |
references/viewsets-views.md |
Views, viewsets, async views |
| Authentication |
references/authentication.md |
JWT, permissions, SimpleJWT |
| Testing |
references/testing-django.md |
APITestCase, fixtures, factories |
Minimal Working Example
The snippet below demonstrates the core MUST DO constraints: indexed fields, select_related, serializer validation, and endpoint permissions.
# models.py
from django.db import models
class Article(models.Model):
title = models.CharField(max_length=255, db_index=True)
author = models.ForeignKey(
"auth.User", related_name="articles"
)
published_at = models.DateTimeField(auto_now_add=True, db_index=True)
class Meta:
ordering = ["-published_at"]
indexes = [models.Index(fields=["author", "published_at"])]
def __str__(self):
return self.title
# serializers.py
from rest_framework import serializers
from .models import Article
class ArticleSerializer(serializers.ModelSerializer):
author_username = serializers.CharField(source="author.username", read_only=True)
class Meta:
model = Article
fields = ["id", "title", "author_username", "published_at"]
def validate_title(self, value):
if len(value.strip()) < 3:
raise serializers.ValidationError("Title must be at least 3 characters.")
return value.strip()
# views.py
from rest_framework import viewsets, permissions
from .models import Article
from .serializers import ArticleSerializer
class ArticleViewSet(viewsets.ModelViewSet):
"""
Uses select_related to avoid N+1 on author lookups.
IsAuthenticatedOrReadOnly: safe methods are public, writes require auth.
"""
serializer_class = ArticleSerializer
permission_classes = [permissions.IsAuthenticatedOrReadOnly]
def get_queryset(self):
return Article.objects.select_related("author").all()
def perform_create(self, serializer):
serializer.save(author=self.request.user)
# tests.py
from rest_framework.test import APITestCase
from rest_framework import status
from django.contrib.auth.models import User
class ArticleAPITest(APITestCase):
def setUp(self):
self.user = User.objects.create_user("alice", password="pass")
def test_list_public(self):
res = self.client.get("/api/articles/")
self.assertEqual(res.status_code, status.HTTP_200_OK)
def test_create_requires_auth(self):
res = self.client.post("/api/articles/", {"title": "Test"})
self.assertEqual(res.status_code, status.HTTP_403_FORBIDDEN)
def test_create_authenticated(self):
self.client.force_authenticate(self.user)
res = self.client.post("/api/articles/", {"title": "Hello Django"})
self.assertEqual(res.status_code, status.HTTP_201_CREATED)
Constraints
MUST DO
- Use
select_related/prefetch_related for related objects
- Add database indexes for frequently queried fields
- Use environment variables for secrets
- Implement proper permissions on all endpoints
- Write tests for models and API endpoints
- Use Django's built-in security features (CSRF, etc.)
MUST NOT DO
- Use raw SQL without parameterization
- Skip database migrations
- Store secrets in settings.py
- Use DEBUG=True in production
- Trust user input without validation
- Ignore query optimization
Output Templates
When implementing Django features, provide:
- Model definitions with indexes
- Serializers with validation
- ViewSet or views with permissions
- Brief note on query optimization
Knowledge Reference
Django 5.0, DRF, async views, ORM, QuerySet, select_related, prefetch_related, SimpleJWT, django-filter, drf-spectacular, pytest-django
Documentation
1---2name: django-expert3description: 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.4license: MIT5---6
7# Django Expert
8
9Senior Django specialist with deep expertise in Django 5.0, Django REST Framework, and production-grade web applications.
10
11## When to Use This Skill
12
13- Building Django web applications or REST APIs
14- Designing Django models with proper relationships
15- Implementing DRF serializers and viewsets
16- Optimizing Django ORM queries
17- Setting up authentication (JWT, session)
18- Django admin customization
19
20## Core Workflow
21
221. **Analyze requirements** — Identify models, relationships, API endpoints
232. **Design models** — Create models with proper fields, indexes, managers → run `manage.py makemigrations` and `manage.py migrate`; verify schema before proceeding
243. **Implement views** — DRF viewsets or Django 5.0 async views
254. **Validate endpoints** — Confirm each endpoint returns expected status codes with a quick `APITestCase` or `curl` check before adding auth
265. **Add auth** — Permissions, JWT authentication
276. **Test** — Django TestCase, APITestCase
28
29## Reference Guide
30
31Load detailed guidance based on context:
32
33| Topic | Reference | Load When |
34|-------|-----------|-----------|
35| Models | `references/models-orm.md` | Creating models, ORM queries, optimization |
36| Serializers | `references/drf-serializers.md` | DRF serializers, validation |
37| ViewSets | `references/viewsets-views.md` | Views, viewsets, async views |
38| Authentication | `references/authentication.md` | JWT, permissions, SimpleJWT |
39| Testing | `references/testing-django.md` | APITestCase, fixtures, factories |
40
41## Minimal Working Example
42
43The snippet below demonstrates the core MUST DO constraints: indexed fields, `select_related`, serializer validation, and endpoint permissions.
44
45```python
46# models.py
47from django.db import models
48
49class Article(models.Model):
50 title = models.CharField(max_length=255, db_index=True)
51 author = models.ForeignKey(
52 "auth.User", on_delete=models.CASCADE, related_name="articles"
53 )
54 published_at = models.DateTimeField(auto_now_add=True, db_index=True)
55
56 class Meta:
57 ordering = ["-published_at"]
58 indexes = [models.Index(fields=["author", "published_at"])]
59
60 def __str__(self):
61 return self.title
62
63# serializers.py
64from rest_framework import serializers
65from .models import Article
66
67class ArticleSerializer(serializers.ModelSerializer):
68 author_username = serializers.CharField(source="author.username", read_only=True)
69
70 class Meta:
71 model = Article
72 fields = ["id", "title", "author_username", "published_at"]
73
74 def validate_title(self, value):
75 if len(value.strip()) < 3:
76 raise serializers.ValidationError("Title must be at least 3 characters.")
77 return value.strip()
78
79# views.py
80from rest_framework import viewsets, permissions
81from .models import Article
82from .serializers import ArticleSerializer
83
84class ArticleViewSet(viewsets.ModelViewSet):
85 """
86 Uses select_related to avoid N+1 on author lookups.
87 IsAuthenticatedOrReadOnly: safe methods are public, writes require auth.
88 """
89 serializer_class = ArticleSerializer
90 permission_classes = [permissions.IsAuthenticatedOrReadOnly]
91
92 def get_queryset(self):
93 return Article.objects.select_related("author").all()
94
95 def perform_create(self, serializer):
96 serializer.save(author=self.request.user)
97```
98
99```python
100# tests.py
101from rest_framework.test import APITestCase
102from rest_framework import status
103from django.contrib.auth.models import User
104
105class ArticleAPITest(APITestCase):
106 def setUp(self):
107 self.user = User.objects.create_user("alice", password="pass")
108
109 def test_list_public(self):
110 res = self.client.get("/api/articles/")
111 self.assertEqual(res.status_code, status.HTTP_200_OK)
112
113 def test_create_requires_auth(self):
114 res = self.client.post("/api/articles/", {"title": "Test"})
115 self.assertEqual(res.status_code, status.HTTP_403_FORBIDDEN)
116
117 def test_create_authenticated(self):
118 self.client.force_authenticate(self.user)
119 res = self.client.post("/api/articles/", {"title": "Hello Django"})
120 self.assertEqual(res.status_code, status.HTTP_201_CREATED)
121```
122
123## Constraints
124
125### MUST DO
126- Use `select_related`/`prefetch_related` for related objects
127- Add database indexes for frequently queried fields
128- Use environment variables for secrets
129- Implement proper permissions on all endpoints
130- Write tests for models and API endpoints
131- Use Django's built-in security features (CSRF, etc.)
132
133### MUST NOT DO
134- Use raw SQL without parameterization
135- Skip database migrations
136- Store secrets in settings.py
137- Use DEBUG=True in production
138- Trust user input without validation
139- Ignore query optimization
140
141## Output Templates
142
143When implementing Django features, provide:
1441. Model definitions with indexes
1452. Serializers with validation
1463. ViewSet or views with permissions
1474. Brief note on query optimization
148
149## Knowledge Reference
150
151Django 5.0, DRF, async views, ORM, QuerySet, select_related, prefetch_related, SimpleJWT, django-filter, drf-spectacular, pytest-django
152
153[Documentation](https://jeffallan.github.io/claude-skills/skills/backend/django-expert/)