How to Generate UUID in Django?

Hi Dev,
In this example, you will learn how to generate uuid in django. you'll learn how to use uuid in django. I’m going to show you about generate uuid django. we will help you to give example of uuid field django example. follow bellow step for how to generate uuid in python django.
In Python, UUID (Universal Unique Identifier) is a Python library that generates 128-bit random objects. It is a standard built-in Python library, so nothing needs to be installed. There are three main algorithms for producing random numbers.
- 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()) 21241464063300
It is frequently used in place of the Django id field. Django assigns an auto-incrementing primary key field to each model by default:
id = models.AutoField(primary_key=True)
If you explicitly specify primary_key=True, Django will not add this field automatically because it detects that you have 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, ) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True)
Users can access other people's data in the frontend by replacing 1 with 2, 3, 4, and so on. We can refer to it as a simple security leak. In these cases, the id field can be replaced with a 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, ) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True)
I Hope It will help you....