UUID as default value in Django model

I have noticed strange default behavior in the 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 this:

 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 this:

 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 the model object and calculates the default value of the model when the wsgi application starts, or what? Why does uuid give the same values ​​in the first case, but different in the second?

Thanks.

+5
source share
2 answers

The problem is the default attribute, which you set as

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

Here you set the default value as not callable, but the value returned by calling uuid.uuid1() when this model class is initialized.

You must set it as default=uuid.uuid1 , which sets it as the called one, and sets a new uuid every time you need to use the new default value.

+16
source

As of Django 1.8, there is a new UUIDField. It is described in the following link, which also describes how to set default values:

https://docs.djangoproject.com/en/1.8/ref/models/fields/#uuidfield

+9
source

Source: https://habr.com/ru/post/1202540/


All Articles