-1

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?

Moswers
  • 45
  • 5

1 Answers1

0

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)
errorinpersona
  • 380
  • 5
  • 17
  • you don't have to perform a **`exists()`** operation at all – JPG Apr 29 '20 at 17:05
  • You don´t have to, BUT it´s recommended as it is more efficient as doing the bool check. Given that he will only need to check for unique uuid4 if he is storing tons of items, this performance + will actually matter. You can look it up here: https://docs.djangoproject.com/en/3.0/ref/models/querysets/#when-querysets-are-evaluated – errorinpersona Apr 29 '20 at 17:15
  • This is unnecessary as the probability of getting a collision is Zero. – JPG Apr 29 '20 at 17:19
  • Well that is the first point of my answer. However he asked how the make sure it is unique, so here is how to do it. Almost zero is not zero. – errorinpersona Apr 29 '20 at 17:20