Creating django objects with a random primary key

前端 未结 6 1510
面向向阳花
面向向阳花 2021-02-08 12:08

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 i

6条回答
  •  梦如初夏
    2021-02-08 12:20

    os.urandom(n) can "Return a string of n random bytes suitable for cryptographic use". Just make sure that n is large enough for 2**(8*n) to be well above the square of the number of "unique" keys you want to identify, and you can make the risk of collision as low as you want. For example, if you think you may end up with maybe a billion transactions (about 2**30), n=8 might suffice (but play it safe and use a somewhat larger n anyway;-).

提交回复
热议问题