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.

referencesviewsets-views.md

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

ViewSets & Views

ModelViewSet

from rest_framework import viewsets, status
from rest_framework.decorators import action
from rest_framework.response import Response
from rest_framework.permissions import IsAuthenticatedOrReadOnly
from django_filters.rest_framework import DjangoFilterBackend

class ProductViewSet(viewsets.ModelViewSet):
    queryset = Product.objects.select_related('category', 'created_by')
    serializer_class = ProductSerializer
    permission_classes = [IsAuthenticatedOrReadOnly]
    filter_backends = [DjangoFilterBackend, filters.SearchFilter, filters.OrderingFilter]
    filterset_fields = ['category', 'is_active']
    search_fields = ['name', 'description']
    ordering_fields = ['price', 'created_at']
    lookup_field = 'slug'

    def get_queryset(self):
        qs = super().get_queryset()
        if self.action == 'list':
            return qs.filter(is_active=True)
        return qs

    def perform_create(self, serializer):
        serializer.save(created_by=self.request.user)

    @action(detail=True, methods=['post'])
    def purchase(self, request, slug=None):
        product = self.get_object()
        quantity = request.data.get('quantity', 1)

        if product.stock < quantity:
            return Response(
                {'error': 'Insufficient stock'},
                status=status.HTTP_400_BAD_REQUEST
            )

        product.stock -= quantity
        product.save()
        return Response({'message': 'Purchase successful'})

    @action(detail=False, methods=['get'])
    def featured(self, request):
        featured = self.get_queryset().filter(is_featured=True)[:10]
        serializer = self.get_serializer(featured, many=True)
        return Response(serializer.data)

Django 5.0 Async Views

from django.http import JsonResponse
from asgiref.sync import sync_to_async

# Async function-based view
async def user_list(request):
    users = await sync_to_async(list)(
        User.objects.all()[:100]
    )
    return JsonResponse({'users': [u.to_dict() for u in users]})

# Async class-based view
from django.views import View

class AsyncProductView(View):
    async def get(self, request, product_id):
        product = await sync_to_async(
            Product.objects.select_related('category').get
        )(pk=product_id)
        return JsonResponse({
            'id': product.id,
            'name': product.name,
            'category': product.category.name,
        })

Generic Views

from rest_framework import generics

class ProductListCreate(generics.ListCreateAPIView):
    queryset = Product.objects.all()
    serializer_class = ProductSerializer
    permission_classes = [IsAuthenticatedOrReadOnly]

class ProductDetail(generics.RetrieveUpdateDestroyAPIView):
    queryset = Product.objects.all()
    serializer_class = ProductSerializer
    lookup_field = 'slug'

URL Configuration

from rest_framework.routers import DefaultRouter

router = DefaultRouter()
router.register('products', ProductViewSet, basename='product')

urlpatterns = [
    path('api/', include(router.urls)),
]

# Generated URLs:
# GET/POST    /api/products/
# GET/PUT/DELETE /api/products/{slug}/
# POST        /api/products/{slug}/purchase/
# GET         /api/products/featured/

Pagination

# settings.py
REST_FRAMEWORK = {
    'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination',
    'PAGE_SIZE': 20,
}

# Custom pagination
from rest_framework.pagination import PageNumberPagination

class LargeResultsSetPagination(PageNumberPagination):
    page_size = 100
    page_size_query_param = 'page_size'
    max_page_size = 1000

class ProductViewSet(viewsets.ModelViewSet):
    pagination_class = LargeResultsSetPagination

Quick Reference

ViewSet Method HTTP Action
list() GET List all
create() POST Create new
retrieve() GET Get one
update() PUT Full update
partial_update() PATCH Partial update
destroy() DELETE Delete
Hook Purpose
get_queryset() Filter queryset
get_serializer_class() Dynamic serializer
perform_create() Pre-save logic
@action() Custom endpoints

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.