3

I would like to generate an ID for each entry in my db table. It would look like this: nov45833.

The first three characters are unique to the name of my table, nov for novel, com for comic, etc. The next 5 digits are a randomly generated number. If I wanted to delete the entry, I would simply call the stored ID for the entry (e.g. .../delete/nov45833) to do so. I would also like the IDs to be unique (so I don't delete the wrong entry).

My original plan was to click a button as I'm filling out my form that will generate a random number and show the value in the specified form field. Then I would complete the form as intended. Here is an example: Codepen

Would I have to do this on the server-side or with JavaScript? I am working with Python, particularly Flask. If you have any questions or think this is stupid, please let me know. Thank you. I am quite inexperienced.

user2986242
  • 477
  • 1
  • 5
  • 19
  • Why random and not sequence? (i.e. Give each time +1) – Elisha Jan 16 '14 at 07:10
  • generate id and check it in database before insert it. – Satish Sharma Jan 16 '14 at 07:11
  • Maybe you want to check python [uuid](http://stackoverflow.com/questions/534839/how-to-create-a-guid-in-python) library – Elisha Jan 16 '14 at 07:14
  • Why not just let the database generate an ID and then store the type separately? Your URLs don't have to map directly to IDs if you don't want them to. – Sean Vieira Jan 16 '14 at 07:50
  • @SeanVieira I haven't learned how to delete posts yet, so I thought that was standard procedure. It seems it would be easier to just use the db's autoincrement. Thanks for the assistance guys. – user2986242 Jan 17 '14 at 21:44

1 Answers1

1

Taking random 5 digits number can result in re-using same id twice (small number space)

You can do one of the following solutions:

  1. Use bigger id space, you can use the standard uuid which looks like 12345678-1234-5678-1234-567812345678. You can see how to use it How to create a GUID/UUID in Python

  2. You can give ids in a certain order, like <last_given_id> +1 each time, this guarantee you don't re-use id until you get to the maximum.

  3. You can also use @Satish Sharma suggestion, to check each time if id is in the db already. However, I don't think this is a good solution. it seems to me like an unwanted big overhead for each insertion.

Community
  • 1
  • 1
Elisha
  • 4,811
  • 4
  • 30
  • 46