mpen
mpen

Reputation: 283043

Random/non-constant default value for model field?

I've got 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'll notice that the default value for key is a random 16-character string. Problem is, I think this value is getting cached and being used several times in a row. Is there any way I can get a different string every time? (I don't care about uniqueness/collisions)

Upvotes: 7

Views: 3228

Answers (1)

Daniel Naab
Daniel Naab

Reputation: 23066

Yes, the default will only be set when the Model metaclass is initialized, not when you create a new instance of SecretKey.

A solution is to make the default value a callable, in which case the function will be called each 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 model's __init__ function, but callables are cleaner and will still work with standard syntax like model = SecretKey(key='blah').

Upvotes: 11

Related Questions