I have a question with the random string in python django.
I have created a django model
class Post(models.Model):
slug = models.SlugField(unique=True,blank=True)
title = models.CharField(max_length=200)
description = models.TextField()
def save(self, *args, **kwargs):
str_ran = "abcdefghijklmnopqrstuvwxyz"
slug = ""
for i in range(5) :
slug = random.choice(str_ran)
self.slug = slug
super(Post, self).save(*args, **kwargs)
But sometimes that's have some error because the slug field is not unique by python random isn't random a unique string.
What should i do? Do you have some recommend for random these string to make sure it will be unique?
CodePudding user response:
you can create uniq index in database and cache errors when you write to database and get collisions
you can use (UUID slag). UUID is generated based on current time, it allows to garanti uniqueness https://docs.python.org/3/library/uuid.html
CodePudding user response:
You should use uuid instead of random.
Python's uuid module provides an implementation compliant with RFC 4122, to generate unique identifiers:
import uuid
slug = str(uuid.uuid4())
If you want to avoid the dashes (-
) you can also use the hexadecimal representation:
slug = uuid.uuid4().hex