← 返回 Skills 市场
pradeepcep

Django REST Framework

作者 pradeepcep · GitHub ↗ · v1.0.0
linuxdarwinwin32 ✓ 安全检测通过
813
总下载
0
收藏
1
当前安装
1
版本数
在 OpenClaw 中安装
/install drf
功能描述
Generate and manage Django REST APIs using DRF with best practices for serializers, viewsets, routing, authentication, optimization, and testing.
使用说明 (SKILL.md)

Django REST Framework

This skill details how to generate, configure, and enhance REST APIs using Django + Django REST Framework (DRF). It includes instructions on project setup, API structure, serializers, viewsets, routing, authentication, performance optimization, testing, and common pitfalls.

Overview

Use this skill when you:

  • Start a Django + Django REST Framework (DRF) project
  • Work on a Django project that uses Django REST Framework (DRF)
  • Work on a Python project that lists djangorestframework in its requirements.txt or pyproject.toml
  • Create REST API endpoints in a Django project
  • Add, modify, or apply best practices for serializers, views, viewsets, permissions, authentication, pagination, filtering in a Django project
  • Optimize database queries and API performance in a Django project

Start a Project

1. Create & Activate Virtual Environment

python3 -m venv .venv
source .venv/bin/activate
pip install django djangorestframework
django-admin startproject project .

2. Create an App

python manage.py startapp [appname or "api"]

3. Configure Django REST Framework

Add to settings.py:

INSTALLED_APPS = [
    "rest_framework",
    appname or "api",
]

REST_FRAMEWORK = {
    "DEFAULT_PERMISSION_CLASSES": [
        "rest_framework.permissions.IsAuthenticated",
    ],
    "DEFAULT_RENDERER_CLASSES": [
        "rest_framework.renderers.JSONRenderer",
    ],
    "DEFAULT_FILTER_BACKENDS": [
        "django_filters.rest_framework.DjangoFilterBackend",
    ],
    "DEFAULT_PAGINATION_CLASS": "rest_framework.pagination.LimitOffsetPagination",
    "PAGE_SIZE": 10,
}

Core Principles

Serializers

  • Prefer ModelSerializer to reduce boilerplate.
  • Keep serializers focused on validation and representation.
  • Use separate serializers for:
    • list vs detail
    • read vs write
    • public vs internal APIs
  • Add serializers to a serializers.py file inside the appropriate Django app

Example:

# File: accounts/serializers.py
class UserSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = ["id", "username", "email"]

Views & ViewSets

  • Use ViewSet or ModelViewSet for standard CRUD APIs.
  • Override get_queryset() instead of filtering in the serializer.
  • Keep views thin, and use features from DRF parent classes as much as possible
  • Always return responses in the configured format (fallback to json)
  • Always put views in the views.py file inside the appropriate Django app

Example:

# File: accounts/views.py
class UserViewSet(ModelViewSet):
    serializer_class = UserSerializer

    def get_queryset(self):
        return User.objects.filter(is_active=True)

Routing

  • Use DRF routers for consistency and discoverability.
  • Avoid deeply nested URLs unless strictly necessary.
  • Put routers in a urls.py file inside the appropriate Django app
  • Make sure the urls.py inside the Django app is included in the main urls.py

Example:

# File: accounts/urls.py
router = DefaultRouter()
router.register("users", UserViewSet)
urlpatterns = router.urls

Example:

# File: project/urls.py

urlpatterns = [
    path("", include("accounts.urls")),
]

Authentication & Permissions

Authentication

  • Prefer stateless authentication for APIs.
  • Token-based or JWT authentication is recommended.
  • Never rely on session authentication for public APIs unless explicitly required.

Permissions

  • Always define explicit permissions.
  • Default to secure (IsAuthenticated) rather than open.
  • Use custom permission classes for fine-grained control.
  • Create custom permissions inside a permissions.py file inside the appropriate Django app.

Example:

permission_classes = [IsAuthenticated]

Pagination, Filtering & Throttling

Pagination

  • Always paginate list endpoints.
  • Avoid returning unbounded querysets.

Filtering

  • Filter in get_queryset() using request parameters.
  • Validate query params explicitly.

Throttling

Protect APIs from abuse:

REST_FRAMEWORK = {
    "DEFAULT_THROTTLE_CLASSES": [
        "rest_framework.throttling.AnonRateThrottle",
        "rest_framework.throttling.UserRateThrottle",
    ],
    "DEFAULT_THROTTLE_RATES": {
        "anon": "100/day",
        "user": "1000/day",
    },
}

Performance Best Practices

Query Optimization

  • Always inspect query counts in list views.
  • Use select_related() for foreign keys.
  • Use prefetch_related() for many-to-many and reverse relations.

Example:

# File: orders/views.py
def get_queryset(self):
    return Order.objects.select_related("customer").prefetch_related("items")

Caching

  • Cache expensive read-heavy endpoints.
  • Use Redis or Memcached.
  • Never cache user-specific responses globally.

Testing

  • Write tests for:
    • serializers
    • permissions
    • edge cases
  • Use APITestCase and APIClient.
  • Test both success and failure paths.

Common Gotchas & Pitfalls

Bulky Views / Bulky Serializers

Avoid putting business logic inside: - serializers - views - permission classes

Instead, use: - service modules - domain logic in models - reusable helper functions

N+1 Query Problems

DRF does not optimize queries automatically. Missing select_related() or prefetch_related() will silently destroy performance.

Silent Security Bugs

Common mistakes: - Forgetting permission classes - Allowing unauthenticated access by default - Exposing writeable fields unintentionally - Exposing passwords or secret fields in response

Always audit: - serializer fields - permission classes - allowed HTTP methods

Assuming Async Behavior

Django REST Framework is primarily synchronous.

Do not assume: - async views improve performance automatically - background tasks belong in request/response cycles

Use task queues (Celery etc.) for long-running work.

Example Commands

python manage.py makemigrations
python manage.py migrate
python manage.py createsuperuser
python manage.py runserver

📝 References

  • Django documentation
  • Django REST Framework documentation
  • Real-world production DRF patterns
安全使用建议
This skill is a coherent, text-only guide for building DRF APIs. Before using it: (1) review the SKILL.md to ensure its commands and recommendations match your project conventions; (2) if you run its shell commands (virtualenv, pip install), do so in a controlled environment (local venv or container) to avoid affecting system-wide Python packages; (3) verify any third-party packages you install come from trusted package indexes; and (4) if you want stricter assurance, copy the guidance and run the steps manually rather than granting an agent automatic execution privileges.
功能分析
Type: OpenClaw Skill Name: drf Version: 1.0.0 The skill bundle provides comprehensive documentation and standard commands for setting up and working with Django REST Framework. All commands listed in `SKILL.md` are typical for Django development (e.g., `python3 -m venv`, `pip install`, `django-admin startproject`, `python manage.py`). There is no evidence of data exfiltration, malicious execution, persistence mechanisms, obfuscation, or prompt injection attempts against the agent to perform actions outside the stated purpose. The content is purely instructional and aligned with its description.
能力评估
Purpose & Capability
The name/description (Django REST Framework scaffolding and best practices) match the SKILL.md content. The only declared runtime requirement is python3, which is appropriate for the described tasks.
Instruction Scope
The SKILL.md stays on-topic: project setup, serializers, viewsets, routing, auth, optimization, and testing. It instructs creating virtualenvs, installing Django/DRF via pip, editing standard Django files (settings.py, views.py, urls.py, serializers.py). It does not instruct reading unrelated system files, accessing environment secrets, or sending data to external endpoints.
Install Mechanism
No install spec is provided (instruction-only), so nothing is downloaded by the registry. The advice to run pip install is expected for Python projects. There are no download URLs or archive extracts that would raise concerns.
Credentials
The skill declares no required environment variables, credentials, or config paths. The guidance references project-local files (requirements.txt, pyproject.toml, settings.py), which is proportionate to the skill's purpose.
Persistence & Privilege
The skill is not force-installed (always:false) and does not request persistent or cross-skill privileges. As an instruction-only skill it will not modify other skills or system-wide agent settings.
如何使用
  1. 确保已安装 OpenClaw(本地或 Docker 部署)
  2. 在对话框中输入安装命令:/install drf
  3. 安装完成后,直接呼叫该 Skill 的名称或使用 /drf 触发
  4. 根据 Skill 的参数说明提供必要输入,即可获得结构化输出
版本历史
v1.0.0
Initial release: Django REST Framework (DRF) skill with modern scaffolding practices. - Detailed guidelines for setting up and configuring DRF projects. - Covers serializers, viewsets, routing, authentication, permissions, pagination, filtering, and performance best practices. - Includes sections about common pitfalls and how to avoid them. - Provides practical examples and command snippets for each stage. - Emphasizes security and query optimization for production-ready APIs.
元数据
Slug drf
版本 1.0.0
许可证
累计安装 1
当前安装数 1
历史版本数 1
常见问题

Django REST Framework 是什么?

Generate and manage Django REST APIs using DRF with best practices for serializers, viewsets, routing, authentication, optimization, and testing. 它是一个面向 Claude Code / OpenClaw 的 AI Agent Skill 插件,目前累计下载 813 次。

如何安装 Django REST Framework?

在 OpenClaw 或 Claude Code 对话框中运行命令「/install drf」即可一键安装,无需额外配置。

Django REST Framework 是免费的吗?

是的,Django REST Framework 完全免费(开源免费),可自由下载、安装和使用。

Django REST Framework 支持哪些平台?

Django REST Framework 跨平台运行,可在任意部署了 OpenClaw / Claude Code 的环境中使用(linux, darwin, win32)。

谁开发了 Django REST Framework?

由 pradeepcep(@pradeepcep)开发并维护,当前版本 v1.0.0。

💬 留言讨论