All skills
jeffallan avatar

/django-expert

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

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.

referencesdrf-serializers.md

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

DRF Serializers

ModelSerializer

from rest_framework import serializers

class ProductSerializer(serializers.ModelSerializer):
    # Read-only computed field
    category_name = serializers.CharField(source='category.name', read_only=True)

    # Write-only for input
    category_id = serializers.PrimaryKeyRelatedField(
        queryset=Category.objects.all(),
        source='category',
        write_only=True
    )

    # Nested read-only
    created_by = UserSerializer(read_only=True)

    class Meta:
        model = Product
        fields = [
            'id', 'name', 'slug', 'description', 'price', 'stock',
            'category_name', 'category_id', 'created_by', 'created_at'
        ]
        read_only_fields = ['slug', 'created_at']

Field-Level Validation

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

    def validate_price(self, value):
        if value < 0:
            raise serializers.ValidationError("Price cannot be negative")
        return value

    def validate_name(self, value):
        if Product.objects.filter(name__iexact=value).exists():
            raise serializers.ValidationError("Product name already exists")
        return value

Object-Level Validation

class OrderSerializer(serializers.ModelSerializer):
    class Meta:
        model = Order
        fields = ['product', 'quantity', 'shipping_address']

    def validate(self, attrs):
        product = attrs['product']
        quantity = attrs['quantity']

        if quantity > product.stock:
            raise serializers.ValidationError({
                'quantity': f'Only {product.stock} items available'
            })

        if not attrs.get('shipping_address') and quantity > 5:
            raise serializers.ValidationError(
                "Shipping address required for large orders"
            )

        return attrs

Nested Serializers

class OrderItemSerializer(serializers.ModelSerializer):
    class Meta:
        model = OrderItem
        fields = ['product', 'quantity', 'price']

class OrderSerializer(serializers.ModelSerializer):
    items = OrderItemSerializer(many=True)

    class Meta:
        model = Order
        fields = ['id', 'user', 'items', 'total', 'created_at']

    def create(self, validated_data):
        items_data = validated_data.pop('items')
        order = Order.objects.create(**validated_data)

        for item_data in items_data:
            OrderItem.objects.create(order=order, **item_data)

        return order

    def update(self, instance, validated_data):
        items_data = validated_data.pop('items', None)

        for attr, value in validated_data.items():
            setattr(instance, attr, value)
        instance.save()

        if items_data is not None:
            instance.items.all().delete()
            for item_data in items_data:
                OrderItem.objects.create(order=instance, **item_data)

        return instance

SerializerMethodField

class ProductSerializer(serializers.ModelSerializer):
    discount_price = serializers.SerializerMethodField()
    is_available = serializers.SerializerMethodField()

    class Meta:
        model = Product
        fields = ['name', 'price', 'discount_price', 'is_available']

    def get_discount_price(self, obj) -> float:
        discount = self.context.get('discount', 0)
        return obj.price * (1 - discount / 100)

    def get_is_available(self, obj) -> bool:
        return obj.stock > 0 and obj.is_active

Quick Reference

Field Type Use Case
CharField(source=...) Computed from related
PrimaryKeyRelatedField FK input
SerializerMethodField Custom computed
Nested Serializer Related objects
Method Purpose
validate_<field>() Single field validation
validate() Cross-field validation
create() Custom creation logic
update() Custom update logic
to_representation() Custom output

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.