Instead of
codes = db().select(db.products.code)   # Grabs all the existing
codes

how about something like,
  # generate random code
  code = generatecode()
  # look to see if a matching code is in the table
  select stored_code from table where stored_code =code
  #  if no code is returned... then the code is unique

Sorry but I didn't have time to convert pseudocode to web2py syntax


On May 26, 2:44 pm, scausten <scaus...@googlemail.com> wrote:
> I'm adding files content to my database with the following code being
> called onvalidation when the form is submitted. It really simply
> generates a 6-digit alphanumeric code as an identifier for the file:
>
> codes = db().select(db.products.code)   # Grabs all the existing codes
> from the database
> while not form.vars.code:
>     code = "".join([random.sample(string.ascii_lowercase
> +string.digits, 1)[0] for i in range(6)])  # Creates a code
>     if not code in codes:  # If its unique...
>         form.vars.code = code   # ...add it into the form vars
>
> It works fine at the moment, but I'm hoping to have several hundred
> thousand files potentially, and I'm worried that the database call to
> pull all existing codes will become a serious bottleneck. The code
> needs to be random and not sequential.
>
> Does anyone have any ideas on how I can do this more elegantly?

Reply via email to