如何使用 UUID [英] How to use UUID
问题描述
我正在尝试为我的 Django 对象获取唯一 ID.在 Django 1.8 中,他们有 UUIDField.我不确定如何使用此字段为模型中的每个对象生成唯一 ID.
I am trying to get unique IDs for my Django objects. In Django 1.8 they have the UUIDField. I am unsure how to use this field in order to generate unique IDs for each object in my model.
这是我的 UUIDField
Here is what I have for the UUIDField
import uuid
from django.db import models
class MyUUIDModel(models.Model):
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
class Person(models.Model):
...
unique_id = MyUUIDModel()
我可以为 UUID 模型重现 id,但每次我都会得到完全相同的 id.例如:
I can reproduce the id for the UUID model, but everytime I do I get the exact same id. For Example:
person = Person.objects.get(some_field = some_thing)
id = person.unique_id.id
id 然后每次都给我相同的 id.出了什么问题,我该如何解决?
id then gives me the same id every time. What is wrong, how do I fix this?
推荐答案
我不知道你为什么要创建 UUID 模型.您可以将 uuid 字段直接添加到 Person 模型中.
I'm not sure why you've created a UUID model. You can add the uuid field directly to the Person model.
class Person(models.Model):
unique_id = models.UUIDField(default=uuid.uuid4, editable=False, unique=True)
每个人都应该有一个唯一的ID.如果您希望 uuid 作为主键,您可以这样做:
Each person should then have a unique id. If you wanted the uuid to be the primary key, you would do:
class Person(models.Model):
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
您当前的代码尚未向此人添加字段.它在您执行 MyUUIDModel() 时创建了一个 MyUUIDModel
实例,并将其保存为类属性.这样做没有意义,每次加载 models.py 时都会创建 MyUUIDModel
.如果你真的想使用 MyUUIDModel,你可以使用 外键
.然后每个人将链接到不同的 MyUUIDModel 实例.
Your current code hasn't added a field to the person. It has created a MyUUIDModel
instance when you do MyUUIDModel(), and saved it as a class attribute. It doesn't make sense to do that, the MyUUIDModel
will be created each time the models.py loads. If you really wanted to use the MyUUIDModel, you could use a ForeignKey
. Then each person would link to a different MyUUIDModel instance.
class Person(models.Model):
...
unique_id = models.ForeignKey(MyUUIDModel, unique=True)
不过,正如我之前所说的,最简单的方法是将 UUID 字段直接添加到人员中.
However, as I said earlier, the easiest approach is to add the UUID field directly to the person.
这篇关于如何使用 UUID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!