Hi guys!
I'm working with an API that wants me to generate opaque "reference IDs" for transactions with their API, in other words, unique references that users can't guess or infer in any way. (is 'infer' proper english?)
This is what I've hacked together currently:
randomRef = randint(0, 99999999999999)
while Transaction.objects.filter(transactionRef = randomRef).count():
randomRef = randint(0, 99999999999999)
Transaction.objects.create(user=user, transactionRef=randomRef, price=999)
unfortunately my database seems to be missing transactions at the moment. I've realized that my method isn't particularly thread safe (say I'm running the same django code on multiple mod_wsgi apache threads, they could all be generating the same randomRef!)
Has anyone got a nicer trick to generate random primary keys for me?
Thanks a lot!
EDIT: All answers were very valid solutions, thanks a lot! I went with marking Amber's as accepted since you guys thought it was the best answer!