0

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?

msln
  • 1,318
  • 2
  • 19
  • 38
  • Check this article out: [Are UUIDs really unique?](https://towardsdatascience.com/are-uuids-really-unique-57eb80fc2a87), you don't really need to be concerned, the chances of that happening are **really really** low. – Abdul Aziz Barkat Jan 24 '21 at 11:43
  • @AbdulAzizBarkat Yes I know the probability is low. But I want to find a solution for preventing this really really low probability. – msln Jan 24 '21 at 11:46

2 Answers2

0

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.

Gaëtan GR
  • 1,380
  • 1
  • 5
  • 21
  • It is not the solution. Adding `unique=True` doesn't solve the problem. just raises IntegrityError if duplicate UUID generated, the main problem I have. – msln Jan 24 '21 at 11:43
  • UUID by default is ``not guaranteed unique but practically unique`` but there is one way that you can make it so, override the save method when saving your instance and add a auto-incremental value to your uuid field, – Gaëtan GR Jan 24 '21 at 11:47
0

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.

Abdul Aziz Barkat
  • 19,475
  • 3
  • 20
  • 33