DEV Community

Cover image for How to use UUID in Django
sevdimali
sevdimali

Posted on

How to use UUID in Django

UUID(Universal Unique Identifier) is a Python library that generates random objects of 128 bits. It is a standard built-in Python library which 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
Enter fullscreen mode Exit fullscreen mode

First, let’s look at how we can use UUID in general:

import uuidp
print(uuid.uuid4())
cae6f5a3-377d-4eaa-8d27-3ff12aece93e
Enter fullscreen mode Exit fullscreen mode

UUID usage in Django
Now, let’s look at using UUID usage in Django.

It is commonly used to replace 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)
Enter fullscreen mode Exit fullscreen mode

In general when we access this model’s detail like below:

https://domain.com/subcriptions/1

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)
Enter fullscreen mode Exit fullscreen mode

As we showed above UUID generates random and it is not predictable.

Thanks for reading. I hope you enjoyed it ❤.
The post first appeared in my blog
Keep Learning..!

Latest comments (0)