在django中生成惟一的id

时间:2022-11-25 11:26:10

I want to generate different/unique id per request in django from models field. I did this but I keep getting the same id.

我想在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

4 个解决方案

#1


39  

UPDATE: If you are using Django 1.8 or superior, @madzohan has the right answer below.

更新:如果您正在使用Django 1.8或superior, @madzohan将给出正确的答案。


Do it like this:

这样做:

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

The reason why is because with the parenthesis you evaluate the function when the model is imported and this will yield an uuid which will be used for every instance created.

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

Without parenthesis you passed just the function needed to be called to give the default value to the field and it will be called each time the model is imported.

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

You can also take this approach:

你也可以采用这种方法:

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

Hope this helps!

希望这可以帮助!

#2


63  

since version 1.8 Django has UUIDField https://docs.djangoproject.com/en/1.8/ref/models/fields/#django.db.models.UUIDField

因为版本1.8 Django有uuuidfield https://docs.djangoproject.com/en/1.8 ref/models/fields/# django.db.models.uidfield

import uuid
from django.db import models

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

#3


8  

If you need or want to use a custom ID-generating function rather than Django's UUID field, you can use a while loop in the save() method. For sufficiently large unique IDs, this will almost never result in more than a single db call to verify uniqueness:

如果您需要或希望使用自定义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()

#4


1  

This answer from Google Code worked for me:

谷歌代码中的这个答案对我有用:

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

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

add:

添加:

from uuid import UUID

从uuid进口uuid

to your generated migration file.

到生成的迁移文件。

#1


39  

UPDATE: If you are using Django 1.8 or superior, @madzohan has the right answer below.

更新:如果您正在使用Django 1.8或superior, @madzohan将给出正确的答案。


Do it like this:

这样做:

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

The reason why is because with the parenthesis you evaluate the function when the model is imported and this will yield an uuid which will be used for every instance created.

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

Without parenthesis you passed just the function needed to be called to give the default value to the field and it will be called each time the model is imported.

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

You can also take this approach:

你也可以采用这种方法:

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

Hope this helps!

希望这可以帮助!

#2


63  

since version 1.8 Django has UUIDField https://docs.djangoproject.com/en/1.8/ref/models/fields/#django.db.models.UUIDField

因为版本1.8 Django有uuuidfield https://docs.djangoproject.com/en/1.8 ref/models/fields/# django.db.models.uidfield

import uuid
from django.db import models

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

#3


8  

If you need or want to use a custom ID-generating function rather than Django's UUID field, you can use a while loop in the save() method. For sufficiently large unique IDs, this will almost never result in more than a single db call to verify uniqueness:

如果您需要或希望使用自定义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()

#4


1  

This answer from Google Code worked for me:

谷歌代码中的这个答案对我有用:

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

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

add:

添加:

from uuid import UUID

从uuid进口uuid

to your generated migration file.

到生成的迁移文件。