Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does UUIDField's 'default' attribute takes care of the uniqueness?

I just jumped into Django for a quick project and I figured there is a UUIDField in the models.

I am using this for an external id field that every model will have to expose the object. Will the default parameter handle the uniqueness or do I have to write it in the save? I mean I know there is practically no chance of values colliding, but just to know how it is done internally

like image 599
Deepankar Bajpeyi Avatar asked Jul 19 '15 09:07

Deepankar Bajpeyi


2 Answers

How does UUID module guarantees unique values each time?

RFC 4122(UUID module specification) specifies three algorithms to generate UUIDs:

  1. Using IEEE 802 MAC addresses as a source of uniqueness
  2. Using pseudo-random numbers
  3. Using well-known strings combined with cryptographic hashing

In all cases the seed value is combined with the system clock and a clock sequence value (to maintain uniqueness in case the clock was set backwards). As a result, the UUIDs generated according to the mechanisms above will be unique from all other UUIDs that have been or will be assigned.

Taken from RFC 4122 Abstract:

A UUID is 128 bits long, and can guarantee uniqueness across space and time.

Note: Due to this uniqueness property of UUIDS, there is no check done by Django internally (as mentioned by @FlipperPA) to check if there already exists another object with the same uuid.

like image 200
Rahul Gupta Avatar answered Sep 28 '22 09:09

Rahul Gupta


Django doesn't enforce the uniqueness of UUIDs. That's because the main use case for UUIDs is to provide an identifier that can be expected to be unique without having to check with a centralized authority (like a database, which is what unique=True does).

(Note that UUIDs are not guaranteed to be unique, there is just an astronomically small chance of a collision.)

You certainly can use the database to enforce uniqueness on top of the UUIDs if you want (by setting unique=True on your field), but I would say that's an unusual, and hard to justify, configuration.

like image 26
Kevin Christopher Henry Avatar answered Sep 28 '22 09:09

Kevin Christopher Henry