Production-Ready Rule
•
**/*.py, apps/**/*.py
Django 5 & Django REST Framework .cursorrules (.mdc)
Enterprise-grade .cursorrules and .cursor/rules/*.mdc configuration for Django 5 and Django REST Framework (DRF). Prevent N+1 queries with select_related/prefetch_related, enforce typed serializers, and clean service layers.
.cursor/rules/django-python.mdc
---
description: Django 5 and Django REST Framework (DRF) backend engineering standards
globs: **/*.py, apps/**/*.py
alwaysApply: false
---
# Django & DRF Engineering Standards
## Query Optimization & N+1 Prevention
- Never loop over foreign-key relations without `select_related()` (for ForeignKey/OneToOne) or `prefetch_related()` (for ManyToMany).
- Use `.only()` or `.values_list()` when fetching lightweight subsets of columns.
- Use `bulk_create()` and `bulk_update()` for batch database operations; never save instances in a loop.
## Architecture & Service Layer
- Keep views thin: views and ViewSets should only parse requests, invoke service functions, and return responses.
- Place core business logic in dedicated `services/*.py` modules rather than fat models or serializers.
- Use ModelSerializer for CRUD validation; explicitly define `fields = [...] ` and never use `fields = '__all__'`.
## Asynchronous & Background Tasks
- Long-running operations (emails, webhooks, heavy reports) MUST be dispatched to Celery tasks with `task.delay()`.
⭐
Using this rule in your open-source project? Reference in your README:
https://cursor.pacebowl.com/rules/django-python
Frequently Asked Questions & Implementation Notes
How does this rule eliminate Django N+1 query bottlenecks?
It scans query access patterns and mandates select_related on forward relations and prefetch_related on reverse/M2M relations before serialization.
Why is fields = "__all__" forbidden in DRF serializers?
fields = "__all__" can unintentionally leak internal model fields (such as password hashes or audit columns) whenever new database columns are added.