How to prevent IntegrityError in case of using UUID in django

435 views Asked by At

I want to use UUID as PK in my django model as follows (database is Postgresql):

class Post(models.Model):
    pk = models.UUID(primary_key=True, unique=True, default=uuid.uuid4, editable=False)
    ...

Every time uuid.uuid4 generates a new UUID.
My question is: Is it possible that uuid.uuid4 generate a duplicate UUID?
And if it's possible, how to prevent IntegrityError in case of duplicate UUID generated?

2

There are 2 answers

2
Gaëtan GR On

The best way to make sure you are not compromising your database but still using the UUID as an identifier is to do the following:

# Or whatever field name suits you best / unique=True for integrity purposes
uuid_pk = models.UUID(unique=True, default=uuid.uuid4, editable=False)

Just make it a secondary key and unique and use the pk provided by Django as normal.

0
Abdul Aziz Barkat On

As per this answer by Bob Aman

Frankly, in a single application space without malicious actors, the extinction of all life on earth will occur long before you have a collision, even on a version 4 UUID, even if you're generating quite a few UUIDs per second.

You really don't need to worry about any duplicates, if you still worry try using uuid1 instead, which has even lesser chances of having duplicates as it uses the machines MAC and timestamps. You can always use a try-except block to check for IntegrityErrors if needed.