Django and DRF: Fast Queries, Safe Migrations, Secure APIs
Builds and reviews Django/DRF code: kills N+1 queries, writes zero-downtime migrations, locks down permissions.
Before & after
Same prompt, same agent — the only difference is the skill.
Django REST Framework is powerful for building APIs. You'd need to set up models to represent your data, create serializers to handle validation and conversion, and write viewsets to handle the HTTP logic. Authentication typically involves tokens, and JWT is a popular choice. You'd configure your settings.py to enable the authentication. Then set up your URL routing. There's also middleware and permissions to think about. What resource do you want to expose through the API?
DJANGO MODEL
class Article(models.Model):
title = models.CharField(max_length=255, db_index=True)
author = models.ForeignKey(User, on_delete=models.CASCADE)
content = models.TextField()
created_at = models.DateTimeField(auto_now_add=True, db_index=True)
updated_at = models.DateTimeField(auto_now=True)
class Meta:
indexes = list(models.Index(fields=tuple('author', '-created_at')))
DRF SERIALIZER
class ArticleSerializer(serializers.ModelSerializer):
author_name = serializers.CharField(source='author.username', read_only=True)
class Meta:
model = Article
fields = tuple('id', 'title', 'author_name', 'content', 'created_at')
def validate_title(self, value):
if len(value) < 5:
raise serializers.ValidationError('Title must be at least 5 chars')
return value
VIEWSET & PERMISSIONS
class ArticleViewSet(viewsets.ModelViewSet):
serializer_class = ArticleSerializer
permission_classes = tuple(IsAuthenticated,)
def get_queryset(self):
return Article.objects.filter(author=self.request.user).select_related('author')
SETTINGS.PY CONFIG
INSTALLED_APPS = tuple(rest_framework,)
REST_FRAMEWORK = dict(DEFAULT_AUTHENTICATION_CLASSES=tuple('rest_framework_simplejwt.authentication.JWTAuthentication',))
URL ROUTING
router = DefaultRouter()
router.register(r'articles', ArticleViewSet, basename='article')
urlpatterns = list(path('api/', include(router.urls)),)
ENDPOINT READY: POST /api/articles/ with JWT token to create, GET /api/articles/ to list user articlesAbout this skill
Your DRF list endpoint takes four seconds. The migration that ran fine locally locked a production table. Someone just noticed users can fetch other users' records by changing an ID. This skill works on Django and DRF code by tracing the SQL each view actually runs, planning migrations around a live deploy, and scoping every queryset to the requesting user.
What it does
- Finds N+1 queries where they actually live: nested serializers,
source='a.b'fields, and SerializerMethodFields. It fixes them inget_querysetwith select_related, Prefetch objects, and annotations, then pins the fix with anassertNumQueriestest. - Catches annotation bugs that inflate totals when Count and Sum span multiple joins.
- Plans migrations for live PostgreSQL tables:
db_default, concurrent indexes, two-phase column drops, and batched data migrations with reverse code. - Reviews viewsets and serializers for data exposure: unscoped querysets,
__all__fields, writable owner fields, unscoped related-ID fields, and object permissions that never run on list views. - Fixes concurrency bugs: lost updates on counters, race-prone
get_or_create, and Celery tasks that run before the transaction commits. - Designs models with deliberate
on_delete, composite and partial indexes, and database constraints.
What you get
Working code, file by file, with a diagnosis up front. For any schema change you get a migration safety note, plus a test or command that proves the fix. Code reviews come back ordered by severity, with the data-exposure and lock risks first.
Best for
Backend developers and small teams running Django or DRF on PostgreSQL in production, especially anyone fighting slow endpoints, preparing risky migrations, or auditing a multi-tenant API.
SKILL.md preview
---
name: django-drf-queries-migrations-apis
description: Builds, fixes, and reviews Django and Django REST Framework code. It traces the SQL each view really runs, plans migrations that survive a live deploy, and scopes every endpoint to the requesting user. Use when the user says "my DRF endpoint is slow", "fix the N+1 in this serializer", "write a Django model for...", "is this migration safe to run in production", "add JWT auth to my API", "review my viewset", "users can see each other's data", or "my Celery task can't find the object I just created".
---
# Django and DRF: Fast Queries, Safe Migrations, Secure APIs
… (sign up to view the full skill)More development skills
View all Development skills →Production Go: Concurrency, Services & Profiling
Production Go code with leak-free goroutines, context-correct services, wrapped errors, and pprof-driven performance fixes.
Backend Feature Build Plan
Builds one backend feature through gates: confirmed requirements, one-screen design, small tested slices, and a deploy/rollback handoff.
Consistent, Safe Application Logging
Adds structured, correlated logs with useful severity, safe fields, bounded volume, and targeted verification.
Reliable WebSocket Messaging and Scaling
Build WebSocket and Socket.IO systems with authorized rooms, reconnect recovery, bounded queues, and multi-node presence.