Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Random/non-constant default value for model field?

Tags:

django

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)

like image 308
mpen Avatar asked Aug 20 '10 21:08

mpen


1 Answers

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').

like image 157
Daniel Naab Avatar answered Oct 13 '22 11:10

Daniel Naab