1.Primary keys and field-level options
Django adds an auto-incrementing id (AutoField) primary key unless a field is explicitly marked primary_key=True — a UUIDField with default=uuid.uuid4 is a common non-sequential alternative. db_index=True and unique=True add a database-level index/constraint; db_column renames just the underlying column, independent of the Python attribute name.
Key features
- Every model gets `id = models.AutoField(primary_key=True)` automatically, unless another field sets primary_key=True
- A UUIDField primary key needs default=uuid.uuid4 (a callable, not uuid.uuid4() — see the mistake below) and usually editable=False
- db_index=True adds a plain database index for faster lookups on that column
- unique=True adds a database-level UNIQUE constraint, enforced by the database itself, not just Django
- db_column renames the underlying database column without changing the Python attribute name used everywhere else
Field-level lookup and naming options
- AutoField (default id)
- Sequential, predictable
- Row 42 was likely created before row 100
- Compact, sortable by creation order
- UUIDField (default=uuid.uuid4)
- Non-sequential — not guessable
- Safe for public-facing URLs
- Needs the callable, not a call: uuid.uuid4
Command
import uuid
class Order(models.Model):
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)default=uuid.uuid4 (the callable, not a call) for a UUID primary key; db_index/unique are enforced by the database itself; db_column renames only the underlying column, not the Python attribute.