Reputation: 497
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.
Upvotes: 3
Views: 2124
Reputation: 4951
Taking random 5 digits number can result in re-using same id twice (small number space)
You can do one of the following solutions:
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
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.
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.
Upvotes: 1