Sunday, September 9, 2012

How many attempts to generate a unique ID?

Hi everyone! First time posting to this group!

I have a model Class where each row has a unique alphanumeric ID string like 'EX39H'.

This is the function I use to generate the code.

def gen_class_code():
  import string
  import random
  size = 5
  max_size = 16
  attempts = 1000
  chars = string.ascii_uppercase + string.digits 

  # lets try <attempts> times to generate unique id, else increase code length
  res = ""
  while (size <= max_size):
    for i in range(attempts):
      temp = ''.join(random.choice(chars) for i in range(size)) 
      if not Class.objects.filter(code=temp).exists():
        res = temp
        break
    if res : break

  return res 

How much would you set the attempts variable to and why?

Thanks in advance
Anton

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To view this discussion on the web visit https://groups.google.com/d/msg/django-users/-/-JYyShU_ciUJ.
To post to this group, send email to django-users@googlegroups.com.
To unsubscribe from this group, send email to django-users+unsubscribe@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/django-users?hl=en.

0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]

<< Home


Real Estate