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?
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:
Just make it a secondary key and unique and use the pk provided by Django as normal.