且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

UUID作为Django模型中的默认值

更新时间:2022-10-18 09:41:10

问题是您设置的默认属性

  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.