Django UUID Primary key


A model by default will use an auto incrementing (integer) primary key. This will give you a sequence of keys 1, 2, 3.

Different primary key types can be set on a model with a small alterations to the model.

A UUID is a universally unique identifier, this is 32 character random identifier which can be used as an ID. This is a good option to use when you do not want sequential ID's assigned to records in your database.When used on PostgreSQL, this stores in a uuid datatype, otherwise in a char(32).

import uuid
from django.db import models

class ModelUsingUUID(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)

The generated key will be in the format 7778c552-73fc-4bc4-8bf9-5a2f6f7b7f47