在模型字段中生成django中的唯一ID [英] Generate unique id in django from a model field

查看:311
本文介绍了在模型字段中生成django中的唯一ID的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在模型字段中在django中为每个请求生成不同/唯一的ID。我做到了这一点,但是我一直保持着相同的身份。

I want to generate different/unique id per request in django from models field. I did this but I keep getting the same 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


推荐答案

更新:如果您使用的是Django 1.8或更高版本,@madzohan在下面提供了正确的答案。

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

这样做:

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

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

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.

没有括号,您只传递需要调用的函数,以将默认值赋给字段,每次导入模型时都会调用它。

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

希望这有帮助!

这篇关于在模型字段中生成django中的唯一ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆