AgentLint 实测验证 100/100实证最佳实践起步模板(基于 929 个 Python 仓库规则)

    Django(Python) CLAUDE.md & AGENTS.md 模板

    前向迁移安全、N+1 查询预防、DRF Serializer 字段白名单与 --reuse-db 快速单测。

    # Django Project — Django Harness
    
    Django 5 + Python 3.12 web application with PostgreSQL, pytest-django, Ruff, and explicit migration checks.
    
    ## Commands
    
    - Sync deps: `uv sync --dev`
    - Fast targeted test: `uv run pytest apps/orders/tests/test_views.py -x -q --reuse-db`
    - Full suite: `uv run pytest -q`
    - Migration drift check: `uv run python manage.py makemigrations --check --dry-run`
    - Lint & system check: `uv run ruff check . && uv run python manage.py check`
    
    ## Rules
    
    - Don't modify committed migration files in `*/migrations/`. Instead generate a new forward migration with `uv run python manage.py makemigrations`. Because mutating applied migrations breaks staging and production databases.
    - Don't use `fields = "__all__"` on ModelForms or DRF serializers. Instead list allowed fields explicitly. Because wildcard exposure allows mass-assignment of staff or billing flags.
    - Don't run database queries inside template loops or serializer `SerializerMethodField` without `select_related` / `prefetch_related`. Because N+1 queries degrade page latency under load.
    - When adding new apps or auth permissions, read `docs/django-conventions.md` first.
    
    ## Continuity & Safety
    
    - Keep `.env`, `db.sqlite3`, and `CLAUDE.local.md` out of git — never hardcode `SECRET_KEY`.
    - Record migration numbers and passing test outputs in `HANDOFF.md`.

    Django(Python) 开源生态中最常采用的工程规则

    参考 4,533 仓库研究中对应主语言生态的高频工程规则采纳率,并结合框架核心防踩坑约束:

    pytest测试

    pytest-django targeted test runs (929 Python corpus repos)

    45.9%426 个仓库
    unit-tests测试

    Model, view, and serializer unit tests (929 Python corpus repos)

    40.9%380 个仓库
    error-handling代码规范

    Explicit transaction and error boundaries (929 Python corpus repos)

    30.4%282 个仓库
    ruff工具链

    Ruff lint and formatting (929 Python corpus repos)

    29.1%270 个仓库
    docker工具链

    Dockerized Django + Postgres local stack (929 Python corpus repos)

    28.6%266 个仓库
    必写验证命令(对应规则 W1 与 W7)
    安装依赖
    uv sync --dev
    快速单测(秒级迭代)
    uv run pytest apps/billing/tests/test_models.py -x -q
    全量测试
    uv run pytest -q
    Lint 与静态检查
    uv run ruff check . && uv run python manage.py check --deploy
    生产构建
    uv run python manage.py makemigrations --check --dry-run
    Django(Python) 项目中 AI 代理常见踩坑
    • 01AI 直接修改已提交的旧 migration 文件而非生成新前向迁移,破坏测试与生产库历史。
    • 02模板循环或 Serializer 中漏用 select_related / prefetch_related 引发隐性 N+1 慢查询。
    • 03在表单或 DRF Serializer 中写 fields = '__all__',暴露权限字段批量赋值风险。

    更多实证验证模板