user2986242
user2986242

Reputation: 497

Is it possible to generate a random and unique 5 digit ID for my sqlite database?

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

Answers (1)

Elisha
Elisha

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:

  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.

Upvotes: 1

Related Questions