Django如何生成uuid?

How does Django generates uuid?

我在 Django 中有一个以这种方式使用 uuid 的模型:

uuid = models.CharField(max_length=100, default=uuid.uuid1)

问题是,当我生成 2 个对象时,一个接一个,我得到了这个:

933e35c4-df1c-11e6-8a53-ace01055799e

然后:

933e35c5-df1c-11e6-8a53-ace01055799e

据我所知,每个uuid都是随机生成的,但是碰撞的概率很低,我得到这2个几乎相同的uuid时,它们究竟是如何生成的? (它仅在第一个块的最后一个数字上有所不同)以及这有多大可能?。有没有更安全的方法来做到这一点?

问题是我有一组客户,每个客户都通过电子邮件获得一个唯一的 uuid,如果他们可以只更改一个字符并获得另一个客户的 uuid,那将是一个问题。

您正在使用 uuid.uuid1,如文档所述:

Generate a UUID from a host ID, sequence number, and the current time.

您应该使用 uuid.uuid4,它会生成一个 随机 uuid。

它使用 uuid.uuid1 来完成(这是您的默认值)。见 docs:

Generate a UUID from a host ID, sequence number, and the current time. If node is not given, getnode() is used to obtain the hardware address. If clock_seq is given, it is used as the sequence number; otherwise a random 14-bit sequence number is chosen.

还有其他算法,也许uuid4就是您要找的。