UUID作为Django模型中的默认值 [英] UUID as default value in Django model

查看:582
本文介绍了UUID作为Django模型中的默认值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我注意到django模型中的默认值的奇怪行为。例如,我们有一个简单的django模型:

  import uuid 
...

class SiteUser(models.Model):
...
username = models.CharField(max_length = 255,verbose_name = u用户名)
activation_key = models.CharField(max_length = verbose_name = u激活密钥,default = uuid.uuid1())

当我创建一个新的用户,之后还有另一个人:

  user_a = SiteUser(username =UserA)
user_a。 save()
user_b = SiteUser(username =UserB)
user_b.save()

Django使2个用户具有相同的 activation_key



但是我这样做: / p>

  user_a = SiteUser(username =UserA)
user_a.activation_key = uuid.uuid1()
user_a.save()
user_b = SiteUser(username =UserB)
user_b.activation_key = uuid.uuid1()
user_b.save()

一切正常Django使用不同的激活键创建了两个用户。



这里发生了什么? Python加载模型对象并在wsgi应用启动时计算模型的默认值?为什么uuid在第一种情况下给出相同的值,但在第二种情况下不同?



谢谢。

解决方案

问题是您设置的默认属性

  activation_key = models.CharField(max_length = 64,verbose_name = u激活密钥,
default = uuid.uuid1())

在这里,您将默认值设置为不可调用,但由 uuid.uuid1()返回的值,当此模型类被初始化。



您应将其设置为 default = uuid.uuid1 ,将其设置为可调用,并且每次需要使用新的默认值时设置新的uuid。


I've noticed the strange behaviour of default value in django model. For example we have a simple django model:

import uuid
...

class SiteUser(models.Model):
    ...
    username = models.CharField(max_length=255, verbose_name=u"Username")
    activation_key = models.CharField(max_length=64, verbose_name=u"Activation key", default=uuid.uuid1())

When I create a new user, and after that another one like that:

user_a = SiteUser(username="UserA")
user_a.save()
user_b = SiteUser(username="UserB")
user_b.save()

Django makes 2 users with the same activation_key

But then I do it like that:

user_a = SiteUser(username="UserA")
user_a.activation_key = uuid.uuid1()
user_a.save()
user_b = SiteUser(username="UserB")
user_b.activation_key = uuid.uuid1()
user_b.save()

Everything works fine and Django creates 2 users with different activation keys.

What's going on here? Python loads model object and calculate the default value of the model when the wsgi app starts up or that? Why uuid gives the same values in the first case but different in second?

Thanks.

解决方案

Problem is the default attribute that you are setting as

activation_key = models.CharField(max_length=64, verbose_name=u"Activation key",
                 default=uuid.uuid1())

Here you are setting the default value as not a callable but value returned by uuid.uuid1() call when this model class is initialized.

You should set it as default=uuid.uuid1 which sets it as callable, and is sets new uuid each time new default value needs to be used.

这篇关于UUID作为Django模型中的默认值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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