What is UUID and How we can use it in Django?
UUID(Universal Unique Identifier) is a Python library that generating random objects of 128 bits. It is a standard built-in Python library that means you don’t need to install anything. There are three main algorithms used for generating randoms:
- Using IEEE 802 MAC addresses as a source of uniqueness
- Using pseudo-random numbers
- Using well-known strings combined with cryptographic hashing
The UUID uses getnode() to retrieve the MAC value on a given system:
import uuid print(uuid.getnode()) 251053329979042
First, let’s look at how we can use UUID in general:
import uuid print(uuid.uuid4()) cae6f5a3-377d-4eaa-8d27-3ff12aece93e
UUID usage in Django
Now, let’s look at using UUID usage in Django.
It is commonly used to replacing the Django id field. By default, Django gives each model auto-incrementing primary key field:
id = models.AutoField(primary_key=True)
if you want to explicitly set the primary key you must specify primary_key=True then Django won’t add this field automatically because it detects that you set it manually.
Now let’s look real example. Assume that you have a Subscription Model
class Subscription (models.Model): name = models.CharField( verbose_name=_("Subcription Name"), help_text=_("Required and unique"), max_length=255, unique=True, ) cdate = models.DateTimeField(auto_now_add=True) udate = models.DateTimeField(auto_now=True)
In general when we access this model’s detail like below:
In the frontend, users can access other’s data by replacing 1 to 2,3,4, etc. We can call it a simple Security leak. For in these cases we can replace the id field with UUID.
class Subscription (models.Model): id = models.UUIDField( primary_key=True, default=uuid.uuid4, editable=False) name = models.CharField( verbose_name=_("Subcription Name"), help_text=_("Required and unique"), max_length=255, unique=True, ) cdate = models.DateTimeField(auto_now_add=True) udate = models.DateTimeField(auto_now=True)
As we showed above UUID generates random and it is not predictable.