Cursor rules for Django 6.1 and 5.2 LTS models with correct ForeignKey naming, null versus blank, database constraints, safe save() overrides and N+1 fixes.
.cursor/rules/django-model-best-practices.mdc. Downloaded files need to be placed in that repository path.---
description: "Cursor rules for Django 6.1 and 5.2 LTS models with correct ForeignKey naming, null versus blank, database constraints, safe save() overrides and N+1 fixes."
globs: "**/*"
alwaysApply: false
---
# Django Model Best Practices
Applies to: Django `models.py` files, model managers and querysets, and the migrations generated from them.
Version baseline: checked against the Django 6.1 documentation (5.2 is the current LTS). Read `requirements`/`pyproject.toml` for the installed Django version and follow it.
## Model definition
- Name models with singular nouns in CapWords (`Book`, not `Books`) and fields in `snake_case`.
- Name a `ForeignKey` after the related object (`author`), not `author_id`. Django creates the `author_id` column and attribute for you; a field named `author_id` would produce `author_id_id`.
- Give every model a `__str__` that identifies the row in the admin and in logs.
- Set `verbose_name`/`verbose_name_plural` only when the default derived from the class name is wrong for users.
- Choose `on_delete` deliberately: `CASCADE` for parts that cannot exist alone, `PROTECT` or `RESTRICT` for records that must not disappear with their parent, `SET_NULL` (which requires `null=True`) for optional links.
```python
from django.db import models
from django.db.models import Q
from django.db.models.functions import Lower
class Book(models.Model):
title = models.CharField(max_length=255)
isbn = models.CharField(max_length=13, unique=True)
author = models.ForeignKey("Author", on_delete=models.PROTECT, related_name="books")
editor = models.ForeignKey(
"Editor", on_delete=models.SET_NULL, null=True, blank=True, related_name="edited_books"
)
subtitle = models.CharField(max_length=255, blank=True)
publication_date = models.DateField(null=True, blank=True)
price = models.DecimalField(max_digits=8, decimal_places=2)
class Meta:
ordering = ["title"]
indexes = [models.Index(fields=["publication_date"])]
constraints = [
models.CheckConstraint(condition=Q(price__gte=0), name="book_price_non_negative"),
models.UniqueConstraint(Lower("title"), "author", name="book_unique_title_per_author"),
]
def __str__(self) -> str:
return self.title
```
## `null` and `blank`
- `null` controls the database column; `blank` controls form and model validation.
- For `CharField` and `TextField`, use `blank=True` and store `""`, not `null=True`. The exception is a `CharField` with both `unique=True` and `blank=True`, which needs `null=True` to avoid duplicate empty strings.
- For non-string optional values (dates, numbers, foreign keys), use `null=True, blank=True`.
- Use `DecimalField` for money, not `FloatField`.
## Integrity in the database
- Express rules that must always hold as `Meta.constraints` (`UniqueConstraint`, `CheckConstraint`) so they are enforced for every write path, including bulk operations and raw SQL.
- Add `Meta.indexes` for columns used in filters and ordering on large tables; confirm with `EXPLAIN` before adding many.
- `CheckConstraint(condition=...)` is the current keyword; projects before Django 5.1 use `check=`.
## Model methods and `save()`
- Put row-level behavior on the model (`book.is_published()`), and table-level queries on a custom `QuerySet`/manager (`Book.objects.published()`).
- Overriding `save()` is supported. Call `super().save(**kwargs)` and pass the keyword arguments through so options such as `update_fields` keep working.
- `save()` overrides and `pre_save`/`post_save` signals do not run for `bulk_create`, `bulk_update` or `QuerySet.update()`. Put invariants that must survive those paths in constraints.
- Prefer explicit methods or service functions over signals for business logic in your own app; reserve signals for decoupling from apps you do not control.
```python
from django.utils.text import slugify
class Article(models.Model):
title = models.CharField(max_length=200)
slug = models.SlugField(max_length=200, unique=True, blank=True)
def save(self, **kwargs):
if not self.slug:
self.slug = slugify(self.title)
super().save(**kwargs)
```
## Query efficiency
- Use `select_related` for forward `ForeignKey`/`OneToOne` access and `prefetch_related` for reverse and many-to-many relations when you iterate and access related objects; that is the fix for N+1 queries.
- Do not add them when the related objects are not used; measure with `assertNumQueries` or Django Debug Toolbar.
- Use `only()`/`values()` for large reads that need a few columns, and `exists()`/`count()` instead of loading rows.
## Migrations
- Generate migrations with `makemigrations` and commit them with the model change; review the generated operations.
- Split data migrations from schema migrations and give `RunPython` a reverse function when possible.
## Verify before finishing
Run these when they are available in the project:
- `python manage.py makemigrations --check --dry-run` (no missing migrations)
- `python manage.py check`
- the test suite, including `assertNumQueries` for views that list related objects
Cursor rules for Next.js 14+ App Router projects updated for Next.js 16 with async params, validated Route Handlers, generateMetadata and proxy.ts in place of middleware.
Cursor rules for strict TypeScript: compiler checks beyond strict, interfaces vs type aliases, real type guards, discriminated unions, utility types and branded IDs.
Cursor rules for Tailwind CSS v4: automatic class sorting, mobile-first breakpoints, CVA variants with merging, class-based dark mode via @custom-variant, and CSS-first @theme configuration.
Cursor
coding
Illustrative input and expected result. This example is a verification guide, not a recorded model run.
Content reviewed .
A Django 5.2 LTS project has this rule attached to models.py while a developer asks Cursor to add a Book model and a list view.
Add a Book model with title, unique ISBN, required author, optional editor, optional publication date and a non-negative price, and make the book list page show author names without extra queries.
Illustrative; not a recorded model run. A Book model with author = ForeignKey(..., on_delete=PROTECT) (not author_id), editor = ForeignKey(..., SET_NULL, null=True, blank=True), subtitle-style strings using blank=True without null=True, DecimalField price, a CheckConstraint for price >= 0 using condition= (check= only before 5.1), __str__, a generated migration, and a view queryset using select_related("author") verified with assertNumQueries.Cursor applies project rules stored as .mdc files in .cursor/rules. Each rule's frontmatter (description, globs, alwaysApply) decides whether it is always included, attached to matching files, chosen by the agent from its description, or only used when you @-mention it. Cursor also reads AGENTS.md in the project root and subdirectories for plain-Markdown instructions.
.cursor/rules/django-model-best-practices.mdcStarting point, not a tested configuration for your repository. Attached when files matching the globs are in context (alwaysApply: false with globs). Review the instructions, adapt the file paths and run your project's existing checks.
---
description: "Django Model Best Practices: Fields, Constraints and Query Efficiency project conventions"
globs: "**/*"
alwaysApply: false
---
# Django Model Best Practices
Applies to: Django `models.py` files, model managers and querysets, and the migrations generated from them.
Version baseline: checked against the Django 6.1 documentation (5.2 is the current LTS). Read `requirements`/`pyproject.toml` for the installed Django version and follow it.
## Model definition
- Name models with singular nouns in CapWords (`Book`, not `Books`) and fields in `snake_case`.
- Name a `ForeignKey` after the related object (`author`), not `author_id`. Django creates the `author_id` column and attribute for you; a field named `author_id` would produce `author_id_id`.
- Give every model a `__str__` that identifies the row in the admin and in logs.
- Set `verbose_name`/`verbose_name_plural` only when the default derived from the class name is wrong for users.
- Choose `on_delete` deliberately: `CASCADE` for parts that cannot exist alone, `PROTECT` or `RESTRICT` for records that must not disappear with their parent, `SET_NULL` (which requires `null=True`) for optional links.
```python
from django.db import models
from django.db.models import Q
from django.db.models.functions import Lower
class Book(models.Model):
title = models.CharField(max_length=255)
isbn = models.CharField(max_length=13, unique=True)
author = models.ForeignKey("Author", on_delete=models.PROTECT, related_name="books")
editor = models.ForeignKey(
"Editor", on_delete=models.SET_NULL, null=True, blank=True, related_name="edited_books"
)
subtitle = models.CharField(max_length=255, blank=True)
publication_date = models.DateField(null=True, blank=True)
price = models.DecimalField(max_digits=8, decimal_places=2)
class Meta:
ordering = ["title"]
indexes = [models.Index(fields=["publication_date"])]
constraints = [
models.CheckConstraint(condition=Q(price__gte=0), name="book_price_non_negative"),
models.UniqueConstraint(Lower("title"), "author", name="book_unique_title_per_author"),
]
def __str__(self) -> str:
return self.title
```
## `null` and `blank`
- `null` controls the database column; `blank` controls form and model validation.
- For `CharField` and `TextField`, use `blank=True` and store `""`, not `null=True`. The exception is a `CharField` with both `unique=True` and `blank=True`, which needs `null=True` to avoid duplicate empty strings.
- For non-string optional values (dates, numbers, foreign keys), use `null=True, blank=True`.
- Use `DecimalField` for money, not `FloatField`.
## Integrity in the database
- Express rules that must always hold as `Meta.constraints` (`UniqueConstraint`, `CheckConstraint`) so they are enforced for every write path, including bulk operations and raw SQL.
- Add `Meta.indexes` for columns used in filters and ordering on large tables; confirm with `EXPLAIN` before adding many.
- `CheckConstraint(condition=...)` is the current keyword; projects before Django 5.1 use `check=`.
## Model methods and `save()`
- Put row-level behavior on the model (`book.is_published()`), and table-level queries on a custom `QuerySet`/manager (`Book.objects.published()`).
- Overriding `save()` is supported. Call `super().save(**kwargs)` and pass the keyword arguments through so options such as `update_fields` keep working.
- `save()` overrides and `pre_save`/`post_save` signals do not run for `bulk_create`, `bulk_update` or `QuerySet.update()`. Put invariants that must survive those paths in constraints.
- Prefer explicit methods or service functions over signals for business logic in your own app; reserve signals for decoupling from apps you do not control.
```python
from django.utils.text import slugify
class Article(models.Model):
title = models.CharField(max_length=200)
slug = models.SlugField(max_length=200, unique=True, blank=True)
def save(self, **kwargs):
if not self.slug:
self.slug = slugify(self.title)
super().save(**kwargs)
```
## Query efficiency
- Use `select_related` for forward `ForeignKey`/`OneToOne` access and `prefetch_related` for reverse and many-to-many relations when you iterate and access related objects; that is the fix for N+1 queries.
- Do not add them when the related objects are not used; measure with `assertNumQueries` or Django Debug Toolbar.
- Use `only()`/`values()` for large reads that need a few columns, and `exists()`/`count()` instead of loading rows.
## Migrations
- Generate migrations with `makemigrations` and commit them with the model change; review the generated operations.
- Split data migrations from schema migrations and give `RunPython` a reverse function when possible.
## Verify before finishing
Run these when they are available in the project:
- `python manage.py makemigrations --check --dry-run` (no missing migrations)
- `python manage.py check`
- the test suite, including `assertNumQueries` for views that list related objects
Ask for a small change to one matching file. Check the tool's loaded context or instruction view, inspect the diff for the requested convention, and run the relevant build or test. A well-formatted file does not guarantee the model follows every instruction.
Cursor's docs recommend keeping individual rules under 500 lines and splitting large rules into composable ones. Cursor's documentation states that it supports AGENTS.md in the project root and in subdirectories. Use AGENTS.md for plain-Markdown instructions you also want other tools to read, and .mdc rules when you need Cursor's scoping options (globs, description-based selection, always-apply).
Documentation checked 2026-11-05: Cursor docs: Rules
Cursor rules for Next.js 14+ App Router projects updated for Next.js 16 with async params, validated Route Handlers, generateMetadata and proxy.ts in place of middleware.
Cursor rules for strict TypeScript: compiler checks beyond strict, interfaces vs type aliases, real type guards, discriminated unions, utility types and branded IDs.
Cursor rules for Tailwind CSS v4: automatic class sorting, mobile-first breakpoints, CVA variants with merging, class-based dark mode via @custom-variant, and CSS-first @theme configuration.