Random / inconsistent default value for model field?

I have a model that looks something like this.

class SecretKey(Model): user = ForeignKey('User', related_name='secret_keys') created = DateTimeField(auto_now_add=True) updated = DateTimeField(auto_now=True) key = CharField(max_length=16, default=randstr(length=16)) purpose = PositiveIntegerField(choices=SecretKeyPurposes) expiry_date = DateTimeField(default=datetime.datetime.now()+datetime.timedelta(days=7), null=True, blank=True) 

You will notice that the default value for key is a random 16-character string. The problem is that I think this value is cached and used several times in a row. Is there a way that I can get a different string every time? (I'm not interested in uniqueness / collisions)

+6
django
source share
1 answer

Yes, the default value will be set only when the Model metaclass is initialized, and not when creating a new SecretKey instance.

The solution is to make the default value of a callable , in which case the function will be called every time a new instance is created.

 def my_random_key(): return randstr(16) class SecretKey(Model): key = CharField(max_length=16, default=my_random_key) 

You could, of course, also set the value in the __init__ function of the model, but the callers are cleaner and will still work with standard syntax like model = SecretKey(key='blah') .

+10
source share

All Articles