Re: How many attempts to generate a unique ID?

158 views
Skip to first unread message

George Silva

unread,
Sep 9, 2012, 7:26:29 PM9/9/12
to django...@googlegroups.com
Do you need this identifier to be so short? If that's not a problem, why don't you use something tried and that's proven that will succeed: GUIDS (or UUIDs).


http://docs.python.org/library/uuid.html

On Sun, Sep 9, 2012 at 8:10 PM, Anton Popovine <anton.p...@gmail.com> wrote:
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...@googlegroups.com.
To unsubscribe from this group, send email to django-users...@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/django-users?hl=en.



--
George R. C. Silva

Desenvolvimento em GIS
http://geoprocessamento.net
http://blog.geoprocessamento.net

Anton Popovine

unread,
Sep 9, 2012, 7:31:45 PM9/9/12
to django...@googlegroups.com
Yes it needs to be short. This will be an invitation string most likely written on a chalk board for kids.

Also there was an error in my initial post : I forgot to increment size += 1 inside the while loop. Noticed right after posting.

thanks
Message has been deleted

Tom Evans

unread,
Sep 10, 2012, 4:57:09 AM9/10/12
to django...@googlegroups.com
On Mon, Sep 10, 2012 at 12:31 AM, Anton Popovine
<anton.p...@gmail.com> wrote:
> Yes it needs to be short. This will be an invitation string most likely
> written on a chalk board for kids.
>
> Also there was an error in my initial post : I forgot to increment size += 1
> inside the while loop. Noticed right after posting.
>
> thanks
>

Have you considered just using a base 36 of the object id?

http://en.wikipedia.org/wiki/Base_36

Cheers

Tom
Reply all
Reply to author
Forward
0 new messages