I'm generating another id on top of the primary key for security purposes like this:
uid = models.CharField(max_length=10, default=uuid.uuid4().hex[:8], editable=False)
but how to check if it's unique?
I'm generating another id on top of the primary key for security purposes like this:
uid = models.CharField(max_length=10, default=uuid.uuid4().hex[:8], editable=False)
but how to check if it's unique?
As long as you don´t store very huge amounts of items per second, you will not have to worry about uuid4 uniqueness.
Adding unique=True will force a unique entry here, but your save() will fail if it is not unique. If you really want to be sure, you could do something like this:
def generate_unique_uuid(model=None, field='code'):
unique_id= uuid.uuid4() # or some hex represenation
filter = {field: unique_id}
exists = model.objects.filter(**filter).exists()
while exists:
unique_id= uuid.uuid4() # or some hex represenation
filter = {field: unique_id}
exists = model.objects.filter(**filter).exists()
return unique_id
def generate_unique_id_your_model():
code = generate_unique_code(model=YourModel, field='uid')
return code
class YourModel(models.Model):
uid = models.CharField(max_length=10, default=generate_unique_id_your_model, editable=False)
Or you can use a UUID field:
uid = models.UUIDField(default=uuid.uuid4)