Python Django + Django Ninja API
Django NinjaによるモダンDjango開発ルール。型安全、非同期対応、Pydanticスキーマ。
You are an expert in Python, Django, and Django Ninja for building modern web APIs.
Key Principles
- Write clean, maintainable Python code following Django's conventions.
- Use Django Ninja for API endpoints instead of Django REST Framework for better performance and type safety.
- Leverage Pydantic schemas for request/response validation.
- Follow Django's app-based architecture for modularity.
Project Structure
project/
apps/
users/
api.py # Django Ninja routers
models.py
schemas.py # Pydantic schemas
services.py # Business logic
tests/
core/
api.py # Main API router
config/
settings/
base.py
local.py
production.py
Django Ninja Guidelines
- Define API routers per app in api.py files.
- Use Schema classes (Pydantic) for request and response types.
- Implement authentication using Django Ninja's built-in decorators.
- Use Path and Query parameters with proper type annotations.
- Implement pagination using Django Ninja's paginate decorator.
- Use async def for I/O-bound endpoints (Django 4.1+ async views).
Models and Database
- Use Django's ORM with proper field types and constraints.
- Define indexes on frequently queried fields.
- Use select_related and prefetch_related to avoid N+1 queries.
- Implement soft deletes where appropriate.
- Use Django migrations for all schema changes.
- Write data migrations for complex data transformations.
Error Handling
- Use Django Ninja's HttpError for API error responses.
- Implement global exception handlers in the API configuration.
- Return consistent error response formats.
- Log errors with proper context for debugging.
Testing
- Use pytest-django for testing.
- Write API tests using Django Ninja's TestClient.
- Test schema validation separately.
- Use factory_boy for test data generation.
- Maintain high test coverage for business logic.
Security
- Use Django's built-in authentication system.
- Implement rate limiting on API endpoints.
- Validate and sanitize all user inputs via Pydantic schemas.
- Use Django's CSRF protection for non-API views.
- Keep secrets in environment variables, never in code.
Performance
- Use Django's caching framework with Redis backend.
- Implement query optimization with Django Debug Toolbar.
- Use Celery for background tasks and long-running operations.
- Enable database connection pooling.
- Use async views for I/O-bound operations.
Refer to Django Ninja documentation for detailed API patterns and Django documentation for ORM best practices. こちらもおすすめ
Backend カテゴリの他のルール
もっとルールを探す
CLAUDE.md、.cursorrules、AGENTS.md、Image Prompts の全 157 ルールをチェック。



