繁体   English   中英

从模型字段在 django 中生成唯一 ID

[英]Generate unique id in django from a model field

我想在 django 中从模型字段为每个请求生成不同/唯一的 id。 我这样做了,但我一直得到相同的 ID。

class Paid(models.Model):
     user=models.ForeignKey(User)
     eyw_transactionref=models.CharField(max_length=100, null=True, blank=True, unique=True, default=uuid.uuid4()) #want to generate new unique id from this field

     def __unicode__(self):
        return self.user

从 1.8 版 Django 开始有了UUIDField

import uuid
from django.db import models

class MyUUIDModel(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    # other fields

如果您使用的是 Django 1.8 或更高版本,那么 madzohan 的答案就是正确的答案。


像这样做:

#note the uuid without parenthesis
eyw_transactionref=models.CharField(max_length=100, blank=True, unique=True, default=uuid.uuid4)

原因是因为在导入模型时使用括号评估函数,这将产生一个 uuid,它将用于创建的每个实例。

没有括号,您只传递了需要调用的函数来为字段提供默认值,并且每次导入模型时都会调用它。

您也可以采用这种方法:

class Paid(models.Model):
     user=models.ForeignKey(User)
     eyw_transactionref=models.CharField(max_length=100, null=True, blank=True, unique=True)

     def __init__(self):
         super(Paid, self).__init__()
         self.eyw_transactionref = str(uuid.uuid4())

     def __unicode__(self):
        return self.user

如果您需要或想要使用自定义 ID 生成函数而不是 Django 的 UUID 字段,您可以在save()方法中使用 while 循环。 对于足够大的唯一 ID,这几乎不会导致超过单个 db 调用来验证唯一性:

urlhash = models.CharField(max_length=6, null=True, blank=True, unique=True)

# Sample of an ID generator - could be any string/number generator
# For a 6-char field, this one yields 2.1 billion unique IDs
def id_generator(size=6, chars=string.ascii_uppercase + string.digits):
    return ''.join(random.choice(chars) for _ in range(size))

def save(self):
    if not self.urlhash:
        # Generate ID once, then check the db. If exists, keep trying.
        self.urlhash = id_generator()
        while MyModel.objects.filter(urlhash=self.urlhash).exists():
            self.urlhash = id_generator()
    super(MyModel, self).save()

来自 Google Code 的这个答案对我有用:

https://groups.google.com/d/msg/south-users/dTyajWop-ZM/-AeuLaGKtyEJ

添加:

from uuid import UUID

到您生成的迁移文件。

您可以将 uuid 用于此任务。 UUIDField 是用于存储通用唯一标识符的特殊字段。 对于primary_key,通用唯一标识符是AutoField 的一个很好的替代方案。 数据库不会为你生成UUID,所以建议使用default。

import uuid
from django.db import models
class MyUUIDModel(models.Model):
   id = models.UUIDField(
     primary_key = True,
     default = uuid.uuid4,
     editable = False)

有关更多详细信息,请访问此链接

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM