Django’s built-in UUIDField makes UUID primary keys straightforward. The only decision is which version to generate: uuid.uuid4 (random) or uuid.uuid7 (time-sortable). For new projects, UUID v7 is the better default — it eliminates B-tree fragmentation without any schema change over UUID v4. See UUID v4 vs v7 for the database index performance analysis.

Model setup — Python 3.13+

# models.py
import uuid
from django.db import models

class Order(models.Model):
    id = models.UUIDField(
        primary_key=True,
        default=uuid.uuid7,   # Python 3.13+; use uuid6.uuid7 for 3.9–3.12
        editable=False,
    )
    customer_id = models.UUIDField()
    status      = models.CharField(max_length=32)
    created_at  = models.DateTimeField(auto_now_add=True)

    class Meta:
        ordering = ['id']   # chronological — UUID v7 sorts by creation time

    def __str__(self):
        return f'Order {self.id}'

For Python 3.9–3.12, install the uuid6 backport:

from uuid6 import uuid7
id = models.UUIDField(primary_key=True, default=uuid7, editable=False)

See Python 3.13 adds uuid.uuid7() for the stdlib addition history.

Migration — switching from UUID v4 to v7

No schema migration is needed. Django stores UUIDs as uuid (PostgreSQL) or char(32) (SQLite/MySQL) — both versions are the same underlying type. Existing rows keep their v4 values; only new inserts change:

# Before
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)

# After — run no migration
id = models.UUIDField(primary_key=True, default=uuid.uuid7, editable=False)

If you need a zero-downtime migration that backfills v7 IDs for existing rows, see Zero-Downtime UUID Migration.

Django REST Framework serializer

# serializers.py
from rest_framework import serializers
from .models import Order

class OrderSerializer(serializers.ModelSerializer):
    class Meta:
        model  = Order
        fields = ['id', 'customer_id', 'status', 'created_at']
        read_only_fields = ['id', 'created_at']

DRF serializes UUIDField as a hyphenated string (xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx) by default — no extra configuration needed. See UUID in OpenAPI for generating format: uuid in DRF’s schema output.

PostgreSQL — server-side UUID v7 (Django 5.x+)

On PostgreSQL 18 with the native uuidv7() function:

# models.py
from django.db import models
from django.db.models.functions import Now

class Order(models.Model):
    id = models.UUIDField(
        primary_key=True,
        db_default=models.expressions.RawSQL("uuidv7()", []),  # PG 18+ only
        editable=False,
    )

db_default (added in Django 5.0) sets the database-layer default — UUID v7 is generated by PostgreSQL even for raw SQL inserts bypassing the ORM. Requires PostgreSQL 18.

Querying by time range

import uuid
from .models import Order

def orders_since(ms: int):
    """Return orders created since a Unix millisecond timestamp."""
    # Build a UUID v7 lower-bound value
    hex_ts = format(ms, '012x')
    lower = uuid.UUID(f'{hex_ts[:8]}-{hex_ts[8:12]}-7000-8000-000000000000')
    return Order.objects.filter(id__gte=lower).order_by('id')

UUID v7’s timestamp prefix allows time-range queries on the primary key index, avoiding a separate index on created_at. See Time Precision for the 48-bit millisecond timestamp structure.

Admin display

# admin.py
from django.contrib import admin
from .models import Order

@admin.register(Order)
class OrderAdmin(admin.ModelAdmin):
    list_display = ['id', 'status', 'created_at']
    list_filter  = ['status']
    ordering     = ['id']   # chronological sort via UUID v7
    readonly_fields = ['id', 'created_at']

Further reading

External references

Frequently asked questions

How do I use UUID v7 as a primary key in Django?

Change the model's default argument from uuid.uuid4 to uuid.uuid7 (Python 3.13+) or uuid6.uuid7 (Python 3.9–3.12). No Django migration is required — the column type is uuid or varchar(32) in both cases. Existing rows keep their UUID v4 values; new inserts use v7. Set ordering = ['id'] in Meta to make ORDER BY id return rows in creation-time order. See UUID in Python — full guide.

Does Django Admin work correctly with UUID v7 primary keys?

Yes. Django Admin treats UUID primary keys as opaque strings — it does not assume sequential integers or parse the UUID format. UUID v7 values sort chronologically in Admin list views when the default ordering uses the id field. For human-readable Admin URLs, consider adding a separate slug field rather than exposing the UUID directly.