Reputation: 1656
I would like to have a field in my model that auto creates a unique primary key for each record.
I've been using:
models.AutoField(primary_key=True)
But this generates simple integer incremented ID's.
What I'd really like is some sort of random 16 digit alphanumeric primary key that is generated automatically and guaranteed to be unique.
What is the best way to implement this?
Upvotes: 0
Views: 955
Reputation: 54
egreene's answer is sufficient, but if you'd like to have more control over your models' UUIDs you can define an abstract base class that automatically assigns a unique UUID using Python's built-in function.
import uuid
from django.db import models
def make_uuid():
"""Return UUID4 string."""
return str(uuid4())
class UUIDModel(models.Model):
uuid = models.CharField(
editable=False, max_length=36, db_index=True,
unique=True, default=make_uuid
)
class Meta:
abstract = True
class RealModel(UUIDModel):
name = models.CharField(max_length=36)
def do_something(self):
pass
The UUIDModel abstract base class could also easily be used as an ingredient in other mix-in abstract classes, letting you mix and match different attributes when making new models.
Upvotes: 2
Reputation: 377
You want to create a UUID field. The extension here django-uuidfield, https://github.com/dcramer/django-uuidfield should work.
After installing with pip install django-uuidfield, you can add the field like so:
from uuidfield import UUIDField
class MyModel(models.Model):
uuid = UUIDField(auto=True)
Disclaimer: the code is from the github README.
Upvotes: 2