django-developer

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Django Developer

Django 开发者

Purpose

用途

Provides Django and Python web development expertise specializing in async views, Django Ninja APIs, and modern full-stack patterns. Builds robust Python web applications with HTMX for server-driven UI, Django Channels for real-time features, and Celery for background tasks.
提供Django和Python Web开发专业知识,专注于异步视图、Django Ninja API和现代全栈模式。使用HTMX构建具备服务器驱动UI的健壮Python Web应用,借助Django Channels实现实时功能,通过Celery处理后台任务。

When to Use

适用场景

  • Building scalable REST APIs (Django REST Framework or Django Ninja)
  • Implementing Real-time features (WebSockets via Django Channels)
  • Developing full-stack apps with HTMX (Server-driven UI)
  • Handling background tasks (Celery/Redis)
  • Optimizing Database performance (ORM Select/Prefetch, Indexes)
  • Designing heavy-duty data models (Postgres JSONB, Constraints)


  • 构建可扩展的REST API(Django REST Framework或Django Ninja)
  • 实现实时功能(通过Django Channels的WebSockets)
  • 开发基于HTMX的全栈应用(服务器驱动UI)
  • 处理后台任务(Celery/Redis)
  • 优化数据库性能(ORM Select/Prefetch、索引)
  • 设计重型数据模型(Postgres JSONB、约束)


2. Decision Framework

2. 决策框架

Architecture Selection

架构选择

What is the project goal?
├─ **API First (Headless)**
│  ├─ Type-safe / Modern? → **Django Ninja** (Pydantic-based, fast)
│  └─ Legacy / Enterprise? → **DRF** (Batteries included, heavy)
├─ **Full Stack (Monolith)**
│  ├─ Complex UI (SPA)? → **Django + React/Vue** (API separation)
│  └─ Dynamic but Simple? → **Django + HTMX** (Hypermedia-driven, no build step)
└─ **Real-Time**
   ├─ Simple updates? → **HTMX Polling** or **SSE**
   └─ Complex/Bi-directional? → **Django Channels (WebSockets)**
What is the project goal?
├─ **API First (Headless)**
│  ├─ Type-safe / Modern? → **Django Ninja** (Pydantic-based, fast)
│  └─ Legacy / Enterprise? → **DRF** (Batteries included, heavy)
├─ **Full Stack (Monolith)**
│  ├─ Complex UI (SPA)? → **Django + React/Vue** (API separation)
│  └─ Dynamic but Simple? → **Django + HTMX** (Hypermedia-driven, no build step)
└─ **Real-Time**
   ├─ Simple updates? → **HTMX Polling** or **SSE**
   └─ Complex/Bi-directional? → **Django Channels (WebSockets)**

Async Strategy (Django 4.2+)

异步策略(Django 4.2+)

FeatureSync (WSGI)Async (ASGI)Recommendation
DB Queries
User.objects.get()
await User.objects.aget()
Use Async for high-concurrency I/O (proxies, chat).
Views
def view(req):
async def view(req):
Keep Sync for CPU-bound tasks.
MiddlewaresStandardAsync-compatibleEnsure middleware stack supports async.
特性同步(WSGI)异步(ASGI)推荐方案
数据库查询
User.objects.get()
await User.objects.aget()
高并发I/O场景(代理、聊天)使用异步。
视图
def view(req):
async def view(req):
CPU密集型任务使用同步。
中间件标准型兼容异步确保中间件栈支持异步。

Database Optimization

数据库优化

  • N+1 Problem: Always check
    select_related
    (Foreign Keys) and
    prefetch_related
    (M2M).
  • Indexing: Use
    GinIndex
    for JSONB search,
    BTree
    for standard lookups.
  • Bulk Ops: Use
    bulk_create
    and
    bulk_update
    for batches > 100 items.
Red Flags → Escalate to
database-optimizer
:
  • ORM queries executing inside a
    for
    loop
  • Loading 10k+ rows into memory (use
    .iterator()
    )
  • "Raw SQL" usage without parameter binding (SQL Injection risk)
  • Locking issues (Select for Update) blocking traffic


  • N+1问题: 务必使用
    select_related
    (外键)和
    prefetch_related
    (多对多)。
  • 索引: 针对JSONB搜索使用
    GinIndex
    ,标准查询使用
    BTree
  • 批量操作: 当批量处理超过100条数据时,使用
    bulk_create
    bulk_update
风险信号 → 移交至
database-optimizer
  • for
    循环内执行ORM查询
  • 加载10000+行数据到内存(使用
    .iterator()
  • 未使用参数绑定的“原生SQL”(存在SQL注入风险)
  • 锁定问题(Select for Update)阻塞流量


Workflow 2: HTMX Integration (Server-Driven UI)

工作流2:HTMX集成(服务器驱动UI)

Goal: Implement an "Infinite Scroll" or "Click to Edit" without writing React.
Steps:
  1. View (Python)
    python
    def contact_list(request):
        contacts = Contact.objects.all()
        # If HTMX request, return only the rows (partial)
        if request.htmx:
            template = "partials/contact_rows.html"
        else:
            template = "contact_list.html"
        
        return render(request, template, {"contacts": contacts})
  2. Template (
    contact_list.html
    )
    html
    <!-- Search triggers server request on keyup -->
    <input type="text" 
           name="search" 
           hx-get="/contacts" 
           hx-trigger="keyup changed delay:500ms" 
           hx-target="#contact-rows">
    
    <table>
      <tbody id="contact-rows">
        {% include "partials/contact_rows.html" %}
      </tbody>
    </table>


目标: 无需编写React即可实现“无限滚动”或“点击编辑”功能。
步骤:
  1. 视图(Python)
    python
    def contact_list(request):
        contacts = Contact.objects.all()
        # If HTMX request, return only the rows (partial)
        if request.htmx:
            template = "partials/contact_rows.html"
        else:
            template = "contact_list.html"
        
        return render(request, template, {"contacts": contacts})
  2. 模板 (
    contact_list.html
    )
    html
    <!-- Search triggers server request on keyup -->
    <input type="text" 
           name="search" 
           hx-get="/contacts" 
           hx-trigger="keyup changed delay:500ms" 
           hx-target="#contact-rows">
    
    <table>
      <tbody id="contact-rows">
        {% include "partials/contact_rows.html" %}
      </tbody>
    </table>


Workflow 4: Async ORM & Views

工作流4:异步ORM与视图

Goal: High-throughput API endpoint using
async/await
.
Steps:
  1. View Definition
    python
    # views.py
    from asgiref.sync import sync_to_async
    
    async def dashboard_stats(request):
        # Parallel DB queries
        user_count_task = User.objects.acount()
        order_count_task = Order.objects.acount()
        
        user_count, order_count = await asyncio.gather(
            user_count_task, 
            order_count_task
        )
    
        return JsonResponse({"users": user_count, "orders": order_count})
  2. Middleware Compatibility
    • Ensure all middlewares are async-capable (
      async_capable = True
      ).
    • If blocking middleware exists, wrap it in
      sync_to_async
      .


目标: 使用
async/await
实现高吞吐量API端点。
步骤:
  1. 视图定义
    python
    # views.py
    from asgiref.sync import sync_to_async
    
    async def dashboard_stats(request):
        # Parallel DB queries
        user_count_task = User.objects.acount()
        order_count_task = Order.objects.acount()
        
        user_count, order_count = await asyncio.gather(
            user_count_task, 
            order_count_task
        )
    
        return JsonResponse({"users": user_count, "orders": order_count})
  2. 中间件兼容性
    • 确保所有中间件均兼容异步(
      async_capable = True
      )。
    • 若存在阻塞型中间件,使用
      sync_to_async
      包裹。


4. Patterns & Templates

4. 模式与模板

Pattern 1: Service Layer (Business Logic)

模式1:服务层(业务逻辑)

Use case: Keeping Views and Models skinny.
python
undefined
适用场景: 保持视图和模型轻量化。
python
undefined

services.py

services.py

class OrderService: @staticmethod def create_order(user, items_data): with transaction.atomic(): order = Order.objects.create(user=user) for item in items_data: OrderItem.objects.create(order=order, **item)
        # Complex logic here
        PaymentGateway.charge(order)
        return order
undefined
class OrderService: @staticmethod def create_order(user, items_data): with transaction.atomic(): order = Order.objects.create(user=user) for item in items_data: OrderItem.objects.create(order=order, **item)
        # Complex logic here
        PaymentGateway.charge(order)
        return order
undefined

Pattern 2: Custom Manager (Query Logic)

模式2:自定义管理器(查询逻辑)

Use case: Reusable filters.
python
class PublishedManager(models.Manager):
    def get_queryset(self):
        return super().get_queryset().filter(status='PUBLISHED', pub_date__lte=timezone.now())

class Article(models.Model):
    # ...
    objects = models.Manager() # Default
    published = PublishedManager() # Custom
适用场景: 可复用的过滤器。
python
class PublishedManager(models.Manager):
    def get_queryset(self):
        return super().get_queryset().filter(status='PUBLISHED', pub_date__lte=timezone.now())

class Article(models.Model):
    # ...
    objects = models.Manager() # Default
    published = PublishedManager() # Custom

Pattern 3: Async Chat (Channels)

模式3:异步聊天(Channels)

Use case: WebSocket handling.
python
undefined
适用场景: WebSocket处理。
python
undefined

consumers.py

consumers.py

class ChatConsumer(AsyncWebsocketConsumer): async def connect(self): self.room_name = "lobby" await self.channel_layer.group_add(self.room_name, self.channel_name) await self.accept()
async def disconnect(self, close_code):
    await self.channel_layer.group_discard(self.room_name, self.channel_name)

async def receive(self, text_data):
    # Broadcast to group
    await self.channel_layer.group_send(
        self.room_name,
        {"type": "chat_message", "message": text_data}
    )

---
---
class ChatConsumer(AsyncWebsocketConsumer): async def connect(self): self.room_name = "lobby" await self.channel_layer.group_add(self.room_name, self.channel_name) await self.accept()
async def disconnect(self, close_code):
    await self.channel_layer.group_discard(self.room_name, self.channel_name)

async def receive(self, text_data):
    # Broadcast to group
    await self.channel_layer.group_send(
        self.room_name,
        {"type": "chat_message", "message": text_data}
    )

---
---

6. Integration Patterns

6. 集成模式

frontend-ui-ux-engineer:

frontend-ui-ux-engineer:

  • Handoff: Django Developer creates HTMX partials (
    _card.html
    ) → UI Dev styles them.
  • Collaboration: Defining "OOB Swaps" (Out of Band) for updating multiple page parts.
  • Tools: Tailwind CSS.
  • 交付: Django开发者创建HTMX片段(
    _card.html
    )→ UI开发者负责样式。
  • 协作: 定义“OOB Swaps”(Out of Band)以更新页面多个部分。
  • 工具: Tailwind CSS。

database-optimizer:

database-optimizer:

  • Handoff: Django Dev logs slow query → DB Optimizer adds Index.
  • Collaboration: Analyzing
    EXPLAIN ANALYZE
    output from ORM generated SQL.
  • Tools: Django Debug Toolbar.
  • 交付: Django开发者记录慢查询→ 数据库优化师添加索引。
  • 协作: 分析ORM生成SQL的
    EXPLAIN ANALYZE
    输出。
  • 工具: Django Debug Toolbar。

devops-engineer:

devops-engineer:

  • Handoff: Django Dev provides
    Dockerfile
    → DevOps configures Gunicorn/Uvicorn.
  • Collaboration: Static files handling (Whitenoise vs S3/CloudFront).
  • Tools: Docker Compose.

  • 交付: Django开发者提供
    Dockerfile
    → DevOps配置Gunicorn/Uvicorn。
  • 协作: 静态文件处理(Whitenoise vs S3/CloudFront)。
  • 工具: Docker Compose。